【发布时间】:2011-12-15 05:11:03
【问题描述】:
在 C# 中,能够使用 .NET System.Graphics.DrawEllipse 方法在从 Windows Calculator (calc.exe) 窗口获取的屏幕设备上下文上绘制一个椭圆。
我希望能够用 GDI32 Ellipse 方法做同样的事情。如何让 Ellipse 绘制到屏幕上?
在下面的代码中,这一行有效: CalculatorGraphics.DrawEllipse(penRed, 50, 50, 50, 50); 但是这条线没有: PlatformInvokeGDI32.Ellipse(hDC, 100, 100, 100, 100); 有什么问题?
//In size variable we shall keep the size of the window.
SIZE size;
//Win32 API functions are imported in classes
//PlatformInvokeGDI32
//PlatformInvokeUSER32.cs
//Get handle of calc.exe window.
IntPtr hwnd = PlatformInvokeUSER32.FindWindow("SciCalc", "Calculator");
//Get window dimensions
PlatformInvokeUSER32.RECT rect;
PlatformInvokeUSER32.GetWindowRect(hwnd, out rect);
size.cx = rect._Right - rect._Left;
size.cy = rect._Bottom - rect._Top;
//Get the device context of Calculator.
IntPtr hDC = PlatformInvokeUSER32.GetDC(hwnd);
//Draw on the Calculator surface.
Graphics CalculatorGraphics = Graphics.FromHdc(hDC);
Color colorRed = Color.FromName("Red");
Pen penRed = new Pen(colorRed);
CalculatorGraphics.DrawEllipse(penRed, 50, 50, 50, 50);
CalculatorGraphics.Save();
PlatformInvokeGDI32.COLORREF cl;
cl.R = 255;
cl.G = 0;
cl.B = 0;
PlatformInvokeGDI32.SetDCBrushColor(hDC, cl);
PlatformInvokeGDI32.SetDCPenColor(hDC, cl);
//PlatformInvokeGDI32.SetBkColor(hDC, cl);
PlatformInvokeGDI32.Ellipse(hDC, 100, 100, 100, 100);
PlatformInvokeGDI32.SaveDC(hDC);
//Here we make a compatible device context in memory for screen device context.
IntPtr hMemDC = PlatformInvokeGDI32.CreateCompatibleDC(hDC);
//Create a compatible bitmap of window size and using screen device context.
m_HBitmap = PlatformInvokeGDI32.CreateCompatibleBitmap(hDC, size.cx, size.cy);
//As m_HBitmap is IntPtr we can not check it against null. For this purspose IntPtr.Zero is used.
if (m_HBitmap != IntPtr.Zero)
{
//Here we select the compatible bitmap in memeory device context and keeps the refrence to Old bitmap.
IntPtr hOld = (IntPtr)PlatformInvokeGDI32.SelectObject(hMemDC, m_HBitmap);
//We copy the Bitmap to the memory device context.
PlatformInvokeGDI32.BitBlt(hMemDC, 0, 0, size.cx, size.cy, hDC, 0, 0, PlatformInvokeGDI32.SRCCOPY);
//We select the old bitmap back to the memory device context.
PlatformInvokeGDI32.SelectObject(hMemDC, hOld);
//We delete the memory device context.
PlatformInvokeGDI32.DeleteDC(hMemDC);
//We release the screen device context.
PlatformInvokeUSER32.ReleaseDC(hwnd, hDC);
//Image is created by Image bitmap handle and returned.
return System.Drawing.Image.FromHbitmap(m_HBitmap);
}
//If m_HBitmap is null retunrn null.
return null;
【问题讨论】:
-
参数的含义不同。您正在绘制一个 0x0 椭圆。
-
谢谢。我现在看到我想要 PlatformInvokeGDI32.Ellipse(hDC, 100, 100, 200, 200);
标签: c# .net winapi graphics gdi