C# 将窗口移动到辅助屏幕

Luk*_*ing 5 c# browser google-chrome

各位开发者大家好

我有一个小问题。我有一个问题开始让我烦恼。

我用 C# 编写了一个程序,可以打开 Chrome 浏览器。但是,Chrome 浏览器始终在上次打开的位置打开。是否有可能在每次启动时将浏览器窗口直接放在第二个屏幕上?我的目标是 Chrome 浏览器始终在另一个屏幕上自动启动。

有人有主意吗?

谢谢

LeR*_*Roi 7

您可以尝试以下操作:

using System;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
Run Code Online (Sandbox Code Playgroud)

……………………

public void StartChrome()
{
    var allScreens = Screen.AllScreens.ToList();

    var screenOfChoice = allScreens[1]; // repllace with your own logic

    var chromeProcess = new Process
    {
            StartInfo =
            {
                    Arguments = "https://www.google.com --new-window --start-fullscreen",
                    FileName = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",
                    WindowStyle = ProcessWindowStyle.Normal
            }
    };

    chromeProcess.Start();

    // Needed to move the the process.
    Thread.Sleep(1000);

    // setting the x value here can help you determmine which screen to move the process to
    // 0 will be the first screen, and the '.WorkingArea.Right' value to the previous screen's '.WorkingArea.Right' would change which 
    // screen to display it on.
    MoveWindow(chromeProcess.MainWindowHandle, screenOfChoice.WorkingArea.Right, screenOfChoice.WorkingArea.Top, screenOfChoice.WorkingArea.Width, screenOfChoice.WorkingArea.Height, false);
}

[DllImport("user32.dll", SetLastError = true)]
internal static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);
Run Code Online (Sandbox Code Playgroud)

编辑:

进一步解释一下,如果您有 3 个屏幕,在该方法中1920x1080设置参数的分辨率会将窗口放置在第一个屏幕的最左侧,设置参数会将应用程序放置在第二个屏幕上,设置参数该过程将显示在第三个屏幕上。通过访问所有屏幕及其宽度,您应该能够几乎始终将进程准确地放置在选择的屏幕上,除非用户对其多屏幕布局进行了自定义排序,那么我不能 100% 确定是否这将是理想的。xMoveWindow()x1920x3840

编辑2:

上面的代码将无法工作.NetCore 2.2并降低,因为它使用System.Windows.Forms我相信只会在.NetCore 3.0