Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

desktop

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.

like image 797
esac Avatar asked Oct 08 '09 07:10

esac


3 Answers

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);
    }
}
like image 107
Paolo Tedesco Avatar answered Sep 17 '22 22:09

Paolo Tedesco


You can try:

Graphics.FromHwnd(IntPtr.Zero)
like image 42
leppie Avatar answered Sep 18 '22 22:09

leppie


You can see a real-world code example within https://uiautomationverify.codeplex.com/SourceControl/latest#UIAVerify/Tools/visualuiverify/utils/screenrectangle.cs

This draws a rectangle that will appear on the screen until the user chooses to remove it at an arbitrary position (wont be repainted over). It uses a windows form thats hidden/ appears as a popup.

This is the code behind the UIAVerify.exe tool in the current Windows SDK.

If you want to use the above, copy the following files into your project:

  • utils\screenboundingrectangle.cs
  • utils\screenrectangle.cs
  • win32\*

Might need to update namespaces accordingly + add references to System.Drawing + System.Windows.Forms

Then you can draw a rectangle with the following code:

namespace Something
{
    public class Highlighter
    {
        ScreenBoundingRectangle _rectangle = new ScreenBoundingRectangle();
        public void DrawRectangle(Rectangle rect)
        {
            _rectangle.Color = System.Drawing.Color.Red;
            _rectangle.Opacity = 0.8;
            _rectangle.Location = rect;
            this._rectangle.Visible = true;
        }
    }
}

and

var rect = Rectangle.FromLTRB(100, 100, 100, 100);
var hi = new Highlighter();
hi.DrawRectangle(rect);
like image 33
Michael Wasser Avatar answered Sep 17 '22 22:09

Michael Wasser