1、名字空间
using System.Runtime.InteropServices;
2、API函数申明
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern IntPtr GetDesktopWindow();//该函数返回桌面窗口的句柄。
[DllImport("user32.dll", EntryPoint = "GetDCEx", CharSet = CharSet.Auto, ExactSpelling = true)]
private static extern IntPtr GetDCEx(IntPtr hWnd, IntPtr hrgnClip, int flags); //获取显示设备上下文环境的句柄
3、绘制代码
private void button4_Click(object sender, EventArgs e)
{
IntPtr desk = GetDesktopWindow();
IntPtr deskDC = GetDCEx(desk, IntPtr.Zero, 0x403);
Graphics g = Graphics.FromHdc(deskDC);
g.DrawString("测试", new Font("宋体", 50, FontStyle.Bold), Brushes.Red, new PointF(100, 100));
}
我注意到绘图使用
Graphics g = Graphics.FromHwnd(form.Handle);
在其控制下在表单背景上绘制。这是你想要完成的吗?
// draw the rectangle
Brush b = new SolidBrush(Color.FromArgb(20, 0, 0, 255));
g.FillRectangle(b, new Rectangle(5, 5, 200, 200));
// clear the rectangle
g.Clear(this.BackColor);
如果我直接在屏幕上绘图,则:
Graphics g = Graphics.FromHwnd(IntPtr.Zero);
Windows 刷新屏幕后,该矩形立即消失。
还有第三种选择,这并不是很简单。
不绘制矩形,而是创建一个降低不透明度、将 TopMost 属性设置为 true 且没有边框的表单。然后使其对事件透明:
protected override void WndProc(ref Message m)
{
const int WM_NCHITTEST = 0x0084;
const int HTTRANSPARENT = (-1);
if (m.Msg == WM_NCHITTEST)
{
m.Result = (IntPtr)HTTRANSPARENT;
}
else
{
base.WndProc(ref m);
}
}
之后您唯一需要注意的是此表单的 Visible、Location 和 Size 属性。
bool change = false;
private void timer1_Tick(object sender, EventArgs e)
{
try
{
if (change)
{
InvalidateRect(IntPtr.Zero, IntPtr.Zero, true);
change = false;
}
else
{
PaintRectangleToScreen();
change = true;
}
}
catch (System.Exception caught)
{
MessageBox.Show(caught.Message);
}
}
标签:IntPtr,C#,CharSet,绘图,Graphics,new,桌面上,true,change From: https://www.cnblogs.com/guangzhiruijie/p/17630775.html