4

I want to draw directly on the desktop ( As wallpaper or over all, I don't mind ) in C#, but I have not been able to find how. I found this:

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 void ReleaseDC(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(desktop);
    }
}

It actually draws a red rectangle but within 1 second, Visual Studio gives me this error:

PInvokeStackImbalance was detected

Any help is appreciated, Thanks

  • I assume you found that code here? http://stackoverflow.com/questions/1536141/how-to-draw-directly-on-the-windows-desktop-c – Zach Johnson Dec 19 '11 at 02:12

2 Answers2

2

you can not draw directly to the desktop with C#. Basically you are going to have to get the bitmap that is being used as the wallpaper, draw on that, then save that to disk and set that as the active wallpaper.

look at this SO question for pointers

Community
  • 1
  • 1
Muad'Dib
  • 28,542
  • 5
  • 55
  • 68
  • Sorry for been unclear but 'Directly' meant 'Not in the Application's window'. But would this be a good way if I want to change the image about 10 times a second? –  Dec 19 '11 at 02:33
2

You could create a top level window that does not have any chrome and then push it to the back of the z-order for the current set of top level windows. Then you would draw into the client area of that window just like any other C# window.

Phil Wright
  • 22,580
  • 14
  • 83
  • 137