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函数实现,基于效率考虑,不想用别的。
[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);
}