Drawing on the Desktop using C#

烈酒焚心 提交于 2020-01-06 20:20:14

问题


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!


回答1:


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.

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);
        }

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.

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




回答2:


You do not need DLL import for this. Use the forms paint event and get the graphics object like this:

private void Form1_Paint(object sender, PaintEventArgs e)
{
    e.Graphics.DrawRectangle(new Pen(Color.Black,3),x,y,width,height);
}


来源:https://stackoverflow.com/questions/35217599/drawing-on-the-desktop-using-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!