C#4.0 GetWindowRect在wpf中

时间:2016-04-05 12:03:07

标签: c# c#-4.0

我想获得我的wpf界面的位置。这个代码可以在c#2.0中工作,但在c#4.0中报告错误。这是代码。

    [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 个答案:

答案 0 :(得分:0)

你应该使用

WindowInteropHelper();

得到句柄,像这样(对于wpf)

  if(!GetWindowRect(new HandleRef(this, new WindowInteropHelper(this).Handle), out rct ))

您可以在https://msdn.microsoft.com/fr-fr/library/system.windows.interop.windowinterophelper%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396

上找到更多文档