问题
I'm trying to create an interface program for the https://www.leapmotion.com device which requires the use of multiple desktop cursors. Since windows doesn't allow multiple cursors, my first task is to create a visual cursor that can be moved around the desktop and other windows.
The way I'm doing it now is to implement a loop and continuously draw the cursor object while clearing it. The drawing part works fine but I have problems doing the clearing part. I've tried using RedrawWindow() in Pinvoke but the code below just breaks during the testing.
Error msg: A call to PInvoke function 'WpfApplication1!WpfApplication1.MainWindow::RedrawWindow' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature.
Appreciate any advice that can be provided.
[DllImport("user32.dll")]
static extern int RedrawWindow(IntPtr hWnd, [In] ref RECT lprcUpdate, IntPtr hrgnUpdate, uint flags);
....
private void Timer_Tick(object sender, EventArgs e)
{
using (Graphics g = Graphics.FromHwnd(IntPtr.Zero))
{
///throw new NotImplementedException();
System.Drawing.Point pt = System.Windows.Forms.Cursor.Position;
System.Drawing.Rectangle rect = new System.Drawing.Rectangle(new System.Drawing.Point(pt.X - 10, pt.Y - 10), new System.Drawing.Size(20, 20));
g.DrawEllipse(Pens.Black, rect);
g.Dispose();
RECT rc = new RECT( pt.X - 20, pt.Y - 20, pt.X + 20, pt.Y + 20 );
RedrawWindow(IntPtr.Zero, ref rc, IntPtr.Zero, 0x0400/*RDW_FRAME*/ | 0x0100/*RDW_UPDATENOW*/| 0x0001/*RDW_INVALIDATE*/);
}
}
Edit:
I've amended the code above as per the suggestions from Alex Farber. (Thanks!)
I've also added the extra ref upon suggestion by Sriram Sakthivel. So now it can compile and run with no errors, however the ellipses drawn are still not being cleared by the RedrawWindow() command.
Any idea what is wrong?
回答1:
I think the problem is you're missing ref in P/Invoke declaration
[DllImport("user32.dll")]
static extern bool RedrawWindow(IntPtr hWnd, [In] ref RECT lprcUpdate, IntPtr hrgnUpdate, uint flags);
and call it as
RedrawWindow(IntPtr.Zero, ref rc, IntPtr.Zero, ...);
^ Note ref keyword here
来源:https://stackoverflow.com/questions/18684323/erasing-drawn-objects-on-desktop-using-pinvoke-on-c-sharp-wpf