C#4.0 GetWindowRect in wpf

非 Y 不嫁゛ 提交于 2020-01-25 19:20:12

问题


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

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