简体   繁体   English

WPF中的C#4.0 GetWindowRect

[英]C#4.0 GetWindowRect in wpf

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. 我想获取我的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;
    }

you should use 你应该使用

WindowInteropHelper();

to get the handle, like this (for wpf) 像这样获取手柄(用于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 : //msdn.microsoft.com/fr-fr/library/system.windows.interop.windowinterophelper%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM