【问题标题】:C# move a window to secondary screenC# 将窗口移动到辅助屏幕
【发布时间】:2019-08-13 10:13:20
【问题描述】:

各位开发者你好

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

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

有人有想法吗?

谢谢

【问题讨论】:

  • 您能否发布一些有关如何打开浏览器的示例代码?

标签: c# google-chrome browser


【解决方案1】:

您可以尝试以下方法:

using System;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;

.......................

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);

编辑:

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

编辑 2:

上述代码不适用于.NetCore 2.2 及更低版本,因为它使用System.Windows.Forms,我相信它只会在.NetCore 3.0 中引入

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-10
    • 2013-01-03
    • 2016-10-21
    • 1970-01-01
    相关资源
    最近更新 更多