How to draw directly on the Windows desktop, C#?

esac picture esac · Oct 8, 2009 · Viewed 24.7k times · Source

This question has been asked for other languages, and even for those other languages, I have found their answers lacking in how to exactly do it, cleanly (no messed up screen repaints, etc..).

Is it possible to draw onto the Windows Desktop from C#? I am looking for an example if possible.

Answer

Paolo Tedesco picture Paolo Tedesco · Oct 8, 2009

Try the following:

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Runtime.InteropServices;

class Program {

    [DllImport("User32.dll")]
    static extern IntPtr GetDC(IntPtr hwnd);

    [DllImport("User32.dll")]
    static extern int ReleaseDC(IntPtr hwnd, IntPtr dc);

    static void Main(string[] args) {
        IntPtr desktop = GetDC(IntPtr.Zero);
        using (Graphics g = Graphics.FromHdc(desktop)) {
            g.FillRectangle(Brushes.Red, 0, 0, 100, 100);
        }
        ReleaseDC(IntPtr.Zero, desktop);
    }
}