[英]How to draw directly on the Windows desktop, C#?
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#? 是否可以从C#绘制到Windows桌面? I am looking for an example if possible.
如果可能的话,我正在寻找一个例子。
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);
}
}
你可以试试:
Graphics.FromHwnd(IntPtr.Zero)
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.exe
tool in the current Windows SDK. 这是当前Windows SDK中
UIAVerify.exe
工具背后的代码。
If you want to use the above, copy the following files into your project: 如果要使用上述内容,请将以下文件复制到项目中:
utils\\screenboundingrectangle.cs
utils\\screenrectangle.cs
win32\\*
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.