问题
I want to get the position of my wpf interface.This code can work in c#2.0,but Report an error in c#4.0.Here is the code.
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetWindowRect(HandleRef hWnd, out RECT lpRect);
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
Rectangle myRect = new Rectangle();
private void button1_Click(object sender, System.EventArgs e)
{
RECT rct;
if(!GetWindowRect(new HandleRef(this, this.Handle), out rct )) //Here is the error
{
MessageBox.Show("ERROR");
return;
}
MessageBox.Show( rct.ToString() );
myRect.X = rct.Left;
myRect.Y = rct.Top;
myRect.Width = rct.Right - rct.Left + 1;
myRect.Height = rct.Bottom - rct.Top + 1;
}
回答1:
you should use
WindowInteropHelper();
to get the handle, like this (for wpf)
if(!GetWindowRect(new HandleRef(this, new WindowInteropHelper(this).Handle), out rct ))
you can find more documentation on : https://msdn.microsoft.com/fr-fr/library/system.windows.interop.windowinterophelper%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396
来源:https://stackoverflow.com/questions/36425884/c4-0-getwindowrect-in-wpf