使用C#在桌面上绘图 [英] Drawing on the Desktop using C#

查看:416
本文介绍了使用C#在桌面上绘图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用C#在桌面上绘制一个矩形。找到一些解决方案后,我得到了:

I'm trying to draw a rectangle right on the desktop using C#. After finding some solutions and I got these:

using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace Test
{
    public partial class Form1 : Form
    {
        [DllImport("User32.dll")]
        public static extern IntPtr GetDC(IntPtr hwnd);
        [DllImport("User32.dll")]

        static extern int ReleaseDC(IntPtr hwnd, IntPtr dc);
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            myFunc();
        }

        public void myFunc()
        {
            IntPtr desktop = GetDC(IntPtr.Zero); 
            using (Graphics g = Graphics.FromHdc(desktop))
            {
                g.FillRectangle(Brushes.Red, 0, 0, 100, 100);
            }
            ReleaseDC(IntPtr.Zero, desktop);
        }
    }
}

但是当我运行它时,屏幕上什么也没有。谁能帮我找出哪一部分出了问题?

But when I run it, I got nothing on my screen. Can anyone help me find out which part goes wrong? It would be much appreciated!

推荐答案

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

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.

这篇关于使用C#在桌面上绘图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆