【问题标题】:Start a program on different screen在不同的屏幕上启动程序
【发布时间】:2018-09-01 13:33:51
【问题描述】:

我已经结账了:

SetWindowPos not working on Form.Show()

Launch an application and send it to second monitor?

但是,这些解决方案似乎都不适合我。我想在不同的显示器上打开一个外部程序。

这是我当前的代码:

 public const int SWP_NOSIZE = 0x0001;
 public const int SWP_NOZORDER = 0x0004;
 public const int SWP_SHOWWINDOW = 0x0040;

 [DllImport("user32.dll", SetLastError = true)]
 public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, int uFlags);


 [DllImport("user32.dll")]
 public static extern bool UpdateWindow(IntPtr hWnd);


 Process application = new Process();
 application.StartInfo.UseShellExecute = false;
 application.StartInfo.FileName = ".......";
 if (application.Start())
 {
     Rectangle monitor = Screen.AllScreens[1].Bounds; // for monitor no 2

     SetWindowPos(
         application.MainWindowHandle,
         IntPtr.Zero,
         monitor.Left,
         monitor.Top,
         monitor.Width,
         monitor.Height,
         SWP_NOZORDER | SWP_NOSIZE | SWP_SHOWWINDOW);
                
     UpdateWindow(application.MainWindowHandle); // tried even with application.Handle
 }

【问题讨论】:

    标签: c# winforms pinvoke setwindowpos


    【解决方案1】:

    首先,您不需要UpdateWindow,调用SetWindowPos 可能就足够了。您只需要确保创建了窗口句柄(因为该进程正在启动)。只需在调用 SetWindowPos 之前添加以下行:

    application.WaitForInputIdle();
    

    如果WaitForInputIdle() 不适合您,您可以尝试以下方法:

    while (application.MainWindowHandle == IntPtr.Zero)
    {
        await Task.Delay(100);
    }
    

    以下代码对我来说很好用:

    Process application = new Process();
    application.StartInfo.UseShellExecute = false;
    application.StartInfo.FileName = "notepad.exe";
    if (application.Start())
    {
        application.WaitForInputIdle();
        /* Optional
        while (application.MainWindowHandle == IntPtr.Zero)
        {
            await Task.Delay(100);
        } */
    
        Rectangle monitor = Screen.AllScreens[1].Bounds; // for monitor no 2
    
        SetWindowPos(
            application.MainWindowHandle,
            IntPtr.Zero,
            monitor.Left,
            monitor.Top,
            monitor.Width,
            monitor.Height,
            SWP_NOZORDER | SWP_NOSIZE | SWP_SHOWWINDOW);
    }
    

    请注意,这只会设置窗口的位置,而不是其大小。如果您还想更改大小,则需要删除 SWP_NOSIZE 标志。

    【讨论】:

      猜你喜欢
      • 2016-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多