C#调用gdi32.dll函数绘制Rectangle填充颜色不起作用什么原因?
大家好,通过搜索代码在Winform C#下调用gdi32.dll做带填充色的矩形橡皮筋,已实现但填充色只能是默认的黑白色,经分析是Brush颜色设定无效,涉及代码如下:
[System.Runtime.InteropServices.DllImportAttribute("gdi32.dll")]
private static extern IntPtr CreateSolidBrush(BrushStyles enBrushStyle, int crColor);
private static extern bool Rectangle(IntPtr hdc, int X1, int Y1, int X2, int Y2);
void Draw(Graphiics g)
{
hdc = g.GetHdc();
gdiPen = CreatePen(penStyle, lineWidth, GetRGBFromColor(Color.FromArgb(255, 255, 255, 232)));// Pen颜色有效
gdiBrush = CreateSolidBrush(brushStyle, GetRGBFromColor(Color.FromArgb(255, 255, 255, 232))); // Brush颜色无论怎么改结果都不变
SelectObject(hdc, gdiPen);
SelectObject(hdc, gdiBrush);
Rectangle(hdc, p1.X, p1.Y, p2.X, p2.Y);
}
如何让设定的Rectangle填充色生效?暂只想用GDI32函数实现,基于效率考虑,不想用别的。

C#调用gdi32.dll函数绘制Rectangle填充颜色不起作用什么原因?
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
1条回答 默认 最新
- 浪客 2022-08-01 09:29关注
[System.Runtime.InteropServices.DllImport("gdi32.dll")] private static extern IntPtr CreateSolidBrush(int crColor); [System.Runtime.InteropServices.DllImport("gdi32.dll")] private static extern bool Rectangle(IntPtr hdc, int X1, int Y1, int X2, int Y2); [System.Runtime.InteropServices.DllImport("gdi32.dll")] public static extern IntPtr CreatePen(int nPenStyle, int nWidth, int crColor); [System.Runtime.InteropServices.DllImport("gdi32.dll")] public static extern IntPtr SelectObject(IntPtr hdc, IntPtr pen); Point p1 = new Point(10, 10), p2 = new Point(200, 100); void Draw(Graphics g) { IntPtr hdc = g.GetHdc(); IntPtr gdiPen = CreatePen(0, 5, GetRGBFromColor(Color.FromArgb(255, 255, 232)));// Pen颜色有效 IntPtr gdiBrush = CreateSolidBrush(GetRGBFromColor(Color.FromArgb(255, 0, 0))); // Brush颜色无论怎么改结果都不变 SelectObject(hdc, gdiPen); SelectObject(hdc, gdiBrush); Rectangle(hdc, p1.X, p1.Y, p2.X, p2.Y); } private int GetRGBFromColor(Color color) { byte r = color.R; byte g = color.G; byte b = color.B; //转化为32bit RGB值: int rgb = (r & 0xff) | ((g & 0xff) << 8) | ((b & 0xff) << 16); return rgb; } private void button1_Click(object sender, System.EventArgs e) { System.Drawing.Graphics gs = pictureBox1.CreateGraphics(); Draw(gs); }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 1无用