【问题标题】:C#4.0 GetWindowRect in wpfwpf 中的 C#4.0 GetWindowRect
【发布时间】:2016-04-05 20:14:52
【问题描述】:

我想得到我的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;
    }

【问题讨论】:

  • 什么错误代码?
  • 错误是未包含“句柄”的定义。
  • 你的班级定义是什么?

标签: c# c#-4.0


【解决方案1】:

你应该使用

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-16
    • 2012-05-27
    • 2011-11-11
    • 2013-11-24
    • 1970-01-01
    • 2011-03-04
    • 1970-01-01
    相关资源
    最近更新 更多