且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用C#在桌面上绘图

更新时间:2021-08-22 21:58:53

可能是窗口刷新了屏幕,所以这就是为什么看不到矩形的原因。屏幕。

probably windows would have refreshed your screen and that's why you don't see the rectangle in your screen.

下面的建议可能不是一个完美的解决方案,但是它可以帮助您使代码正常工作。

The below suggestion may not be a perfect solution, but it may help you to get your code to work.

按照@vivek verma的建议在表单中添加一个绘画处理程序,然后将代码移入该绘画处理程序内

Add a paint handler to your form as @vivek verma suggested and move your code inside this paint handler

private void Form1_Paint(object sender, PaintEventArgs e)
        {
            IntPtr desktop = GetDC(IntPtr.Zero);
            using (Graphics g = Graphics.FromHdc(desktop))
            {
                g.FillRectangle(Brushes.Red, 0, 0, 100, 100);
            }
            ReleaseDC(IntPtr.Zero, desktop);
        }

这将使在重新绘制表单时在屏幕上重新绘制矩形。但是,请记住,当Windows刷新屏幕时,您在屏幕上的绘图将消失。

This will make the rectangle being redrawn in your screen when your form will be repainted. But still remember that your drawing on the screen will be gone when the screen is refreshed by windows.

编辑:
这里还有一个不错的帖子在无格式的屏幕上绘制,这建议使用无边界格式的另一种解决方案。

There is also a good post here draw on screen without form that suggests an alternate solution of using borderless form.