问题
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!
回答1:
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.
回答2:
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);
}
来源:https://stackoverflow.com/questions/35217599/drawing-on-the-desktop-using-c-sharp