Using System.Drawing to draw a crosshair on the desktop?

和自甴很熟 提交于 2020-02-07 07:14:41

问题


I'm trying to create a very small c# utility application that will utilize System.Drawing to draw a full screen, static, fixed cross-hair on my desktop so that I can align some desktop items to the relevant screen center.

I tried looking up a few examples but didn't come up with a whole lot and was wondering if anyone had any experience in this area.

I would prefer not making a transparent full screen window to accomplish this feat if possible.


回答1:


Loads of issues come up when you try this. For one thing, you don't own the desktop, so you never have complete control of it as to when it gets invalidated.

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

[DllImport("User32.dll")]
static extern void ReleaseDC(IntPtr dc);

private void DrawDeskTop()
{
  IntPtr desk = GetDC(IntPtr.Zero);
  using (Graphics g = Graphics.FromHdc(desk))
  {
    g.FillRectangle(Brushes.Red, new Rectangle((SystemInformation.WorkingArea.Width / 2) - 4, (SystemInformation.WorkingArea.Height / 2) - 20, 8, 40));
    g.FillRectangle(Brushes.Red, new Rectangle((SystemInformation.WorkingArea.Width / 2) - 20, (SystemInformation.WorkingArea.Height / 2) - 4, 40, 8));
  }
  ReleaseDC(desk);
}

When this runs, it will look great. But as soon as you move your form over the center or move other windows, the plus sign will disappear, so you will have to draw it again, and again, and again.




回答2:


You can't draw on the desktop at the native level (possibly excluding some hacked in support for Win16 that would disable composition and all sorts of other horribleness), so certainly not with System.Drawing. To do this, you would have to create a transparent window of at least the size of the image and draw on that.




回答3:


Do you have a reason for wanting to use code to accomplish this? I would use your favorite paint program and create an Image. Set that Image as your desktop background and that should give you the same result as what your asking to do in code (and much quicker).

If you have to do this with code I would look into using WPF. It will simplify the transparancy issue. However, you still have an app up over the top of your desktop. You will have to deal with that issue (and maybe a few others).



来源:https://stackoverflow.com/questions/6988774/using-system-drawing-to-draw-a-crosshair-on-the-desktop

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