如何直接在Windows桌面上绘图,C#?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1536141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to draw directly on the Windows desktop, C#?
提问by esac
This question has been asked for other languages, and even for those other languages, I have found their answers lacking in how to exactly do it, cleanly (no messed up screen repaints, etc..).
这个问题已经被问到其他语言,即使是那些其他语言,我发现他们的答案缺乏如何准确地、干净地(没有混乱的屏幕重绘等)。
Is it possible to draw onto the Windows Desktop from C#? I am looking for an example if possible.
是否可以从 C# 绘制到 Windows 桌面上?如果可能的话,我正在寻找一个例子。
采纳答案by Paolo Tedesco
Try the following:
请尝试以下操作:
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);
}
}
回答by leppie
You can try:
你可以试试:
Graphics.FromHwnd(IntPtr.Zero)
回答by Michael Wasser
You can see a real-world code example within https://uiautomationverify.codeplex.com/SourceControl/latest#UIAVerify/Tools/visualuiverify/utils/screenrectangle.cs
您可以在https://uiautomationverify.codeplex.com/SourceControl/latest#UIAVerify/Tools/visualuiverify/utils/screenrectangle.cs 中看到真实的代码示例
This draws a rectangle that will appear on the screen until the user chooses to remove it at an arbitrary position (wont be repainted over). It uses a windows form thats hidden/ appears as a popup.
这将绘制一个将出现在屏幕上的矩形,直到用户选择在任意位置将其删除(不会重新绘制)。它使用隐藏/显示为弹出窗口的窗体。
This is the code behind the UIAVerify.exetool in the current Windows SDK.
这是UIAVerify.exe当前 Windows SDK 中该工具背后的代码。
If you want to use the above, copy the following files into your project:
如果要使用上述内容,请将以下文件复制到您的项目中:
utils\screenboundingrectangle.csutils\screenrectangle.cswin32\*
utils\screenboundingrectangle.csutils\screenrectangle.cswin32\*
Might need to update namespaces accordingly + add references to System.Drawing+ System.Windows.Forms
可能需要相应地更新命名空间 + 添加对System.Drawing+ 的引用System.Windows.Forms
Then you can draw a rectangle with the following code:
然后你可以用下面的代码绘制一个矩形:
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;
}
}
}
and
和
var rect = Rectangle.FromLTRB(100, 100, 100, 100);
var hi = new Highlighter();
hi.DrawRectangle(rect);

