1

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!

Vikash Pandey
  • 5,407
  • 6
  • 41
  • 42
River
  • 23
  • 1
  • 5

2 Answers2

2

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.

Community
  • 1
  • 1
bkdev
  • 432
  • 4
  • 9
  • 1
    The borderless way works, but I still curious why the fist method doesn't take effect. I move codes inside Form1_Paint and add listener on it. But still see nothing:( Finally appreciate your reply! – River Feb 05 '16 at 08:03
-1

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);
}
Vivek Verma
  • 333
  • 3
  • 13
  • I want to draw directly on the windows desktop. Is there anyway to reach that in C#? thx for your reply. – River Feb 05 '16 at 06:46
  • He needs to draw on desktop, not on window. Problem is, that drawing needs to be repainted when needed and that has to be detected somehow. – Ondřej Aug 04 '22 at 09:08