这个问题已经被提出并询问过其他语言,在那些语言中,我发现它们的答案在如何干净地实现(没有糟糕的屏幕重绘等)方面缺乏精确的解释。
能否从C#向Windows桌面绘图?如果可能的话,请给出一个示例。
请尝试以下方法:
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Runtime.InteropServices;
class Program {
[DllImport("User32.dll")]
static extern IntPtr GetDC(IntPtr hwnd);
[DllImport("User32.dll")]
static extern int ReleaseDC(IntPtr hwnd, IntPtr dc);
static void Main(string[] args) {
IntPtr desktop = GetDC(IntPtr.Zero);
using (Graphics g = Graphics.FromHdc(desktop)) {
g.FillRectangle(Brushes.Red, 0, 0, 100, 100);
}
ReleaseDC(IntPtr.Zero, desktop);
}
}
DllImport
语句,所以我真的不知道为什么我选择了错误的 ReleaseDC 签名... - Paolo TedescoGraphics.FromHwnd(IntPtr.Zero)
UIAVerify.exe
工具的代码背后。utils\screenboundingrectangle.cs
utils\screenrectangle.cs
win32\*
System.Drawing
和System.Windows.Forms
的引用。namespace Something
{
public class Highlighter
{
ScreenBoundingRectangle _rectangle = new ScreenBoundingRectangle();
public void DrawRectangle(Rectangle rect)
{
_rectangle.Color = System.Drawing.Color.Red;
_rectangle.Opacity = 0.8;
_rectangle.Location = rect;
this._rectangle.Visible = true;
}
}
}
并且
var rect = Rectangle.FromLTRB(100, 100, 100, 100);
var hi = new Highlighter();
hi.DrawRectangle(rect);