Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/280.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将C#Windows窗体居中放置在另一个窗口中_C#_Winforms_Center - Fatal编程技术网

将C#Windows窗体居中放置在另一个窗口中

将C#Windows窗体居中放置在另一个窗口中,c#,winforms,center,C#,Winforms,Center,我希望我的表单启动并在中心相对于调用表单时处于活动状态的窗口打开。假设Firefox处于活动状态,我显示表单,我希望我的表单显示在Firefox窗口的“中心” 我认为实现这一点的一种方法是使用user32.dll中的SetWindowPos,但我很抱歉 不太确定是否有更简单的方法 我已经使用过SetWindowPos,发现我可以轻松地在整个屏幕上居中显示我的窗口,但我不太确定应该从哪里开始相对于另一个窗口居中显示 基本上,我需要: 抓取窗口位置/大小 做数学运算,找出中心的坐标减去我的表格尺寸

我希望我的表单启动并在中心相对于调用表单时处于活动状态的窗口打开。假设Firefox处于活动状态,我显示表单,我希望我的表单显示在Firefox窗口的“中心”

我认为实现这一点的一种方法是使用user32.dll中的SetWindowPos,但我很抱歉 不太确定是否有更简单的方法

我已经使用过SetWindowPos,发现我可以轻松地在整个屏幕上居中显示我的窗口,但我不太确定应该从哪里开始相对于另一个窗口居中显示

基本上,我需要:

  • 抓取窗口位置/大小
  • 做数学运算,找出中心的坐标减去我的表格尺寸
  • 显示我的表单并使用设置窗口位置来正确定位它

  • 注意:CenterParent对此不起作用,它似乎只适用于另一个表单控件。我想在其他窗口中使用它,例如Firefox。

    如果您希望将新窗口相对于父窗口居中,那么您可以将子窗体的“StartPosition”设置为“CenterParent”。如果您希望将新窗口相对于其他窗口居中,那么我认为您已经处理了Windows API

    [DllImport("user32.dll")]  
    static extern IntPtr GetForegroundWindow();  
    
    
    private IntPtr GetActiveWindow()  
    {  
        IntPtr handle = IntPtr.Zero;  
        return GetForegroundWindow();  
    }
    
    Then get the window position with GetWindowRect.
    
    [DllImport("user32.dll")]  
    [return: MarshalAs(UnmanagedType.Bool)]  
    static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);  
    
    [StructLayout(LayoutKind.Sequential)]  
    public struct RECT  
    {
        public int Left;        // x position of upper-left corner  
        public int Top;         // y position of upper-left corner  
        public int Right;       // x position of lower-right corner  
        public int Bottom;      // y position of lower-right corner  
    }
    

    同样,相对于我激活的窗口,这似乎不起作用。CenterParent似乎仅适用于Windows窗体控件。当我在firefox上尝试时,它只在屏幕的左上角启动。@Steven Colgrove-我想你必须使用user32.dll才能获得当前活动窗口的位置。我想知道它的代码,我可以给你。:)我不认为他想把一个窗口放在父窗口的中心,而是一个任意的窗口。比布,我想举个例子。我对使用这样的外部电话不是很有经验。非常感谢。我将粘贴回我所做的任何添加,这将允许我进入这个窗口的中心:D