【问题标题】:How to programmatically start an application on a specific monitor on Windows 10?如何以编程方式在 Windows 10 上的特定显示器上启动应用程序?
【发布时间】:2018-08-13 12:55:09
【问题描述】:

我想编写一个程序,该程序有时需要在 Windows 10 版本 1803(2018 年 4 月更新)上启动另一个应用程序(主要是 Sumatra PDF)的进程。

这些应用程序应该在特定的监视器上启动。我还希望能够在需要时关闭进程。

首选语言是 C# 和 Java,但欢迎提供任何帮助。

编辑

我尝试在 C++ 代码中直接使用 ShellExecuteExW 函数 suggested by IInspectable,但它不起作用,因为应用程序出现在主监视器上。我肯定犯了一个错误,因为我对 WinAPI 完全陌生,而且对 C++ 知之甚少。

#include <Windows.h>

HMONITOR monitors[2]; // As it's only a test and I have currently only two monitors.
int monitorsCount = 0;

BOOL CALLBACK Monitorenumproc(HMONITOR hMonitor, HDC hdc, LPRECT lprect, LPARAM lparam)
{
    monitors[monitorsCount] = hMonitor;
    monitorsCount++;

    return TRUE;
}

int main()
{
    EnumDisplayMonitors(NULL, NULL, Monitorenumproc, 0);

    _SHELLEXECUTEINFOW info;
    ZeroMemory(&info, sizeof(info));
    info.cbSize = sizeof(info);
    info.fMask = SEE_MASK_HMONITOR;
    //info.lpVerb = L"open";
    info.lpFile = L"C:\\Windows\\System32\\cmd.exe";
    info.nShow = SW_SHOW;
    info.hMonitor = monitors[1]; // Trying to start on the second monitor.

    ShellExecuteExW(&info);

    return 0;
}

【问题讨论】:

  • @IInspectable 感谢您的建议!并为我迟到的回复感到抱歉。我用ShellExecuteEx 试过这个方法,但它对我不起作用。我从 .NET 调用了 WinAPI。也许我刚刚做错了什么,因为它甚至对cmd.exe 都不起作用。同时我只想问你这种方法是否适用于任何应用程序还是依赖于应用程序?
  • @IInspectable 我添加了我的 C++ 代码,它使用 ShellExecuteExW 并且对我也不起作用。如果可以的话,请看一下。
  • 您可以通过简单地使用 ZeroMemory() 来避免所有这些行分配 NULL。您调用 ZeroMemory() 将内存块设置为 0(NULL),然后只分配您实际需要的结构的成员。如果你想要默认操作,你也不应该设置lpVerb
  • @KenWhite 谢谢。我完全忘记了 C++ 中的 memsetting。我已经清理了代码。

标签: windows winapi process windows-10 multiple-monitors


【解决方案1】:

正如其他人所建议的那样,这是 Windows 的预期行为,并且有充分的理由。

此外,您至少不能依赖 SumatraPDF 的默认窗口放置,因为它肯定不使用 CW_USEDEFAULT,而是将这些值存储在:

%USERPROFILE%\AppData\Roaming\SumatraPDF\SumatraPDF-settings.txt

虽然有多种选择:

  1. 使用第三方工具监控顶级窗口,并根据预先配置的规则将它们移动到指定的显示。例如。 DisplayFusion 等。
  2. 使用重量更轻的解决方案,例如 AutoHotkey/AutoIt。
  3. 尝试在代码本身中执行此操作。以下是一个工作解决方案。我在我的盒子上进行了吸烟测试。

免责声明:我没有编写完整的代码,为了节省时间,我从几个来源中提取了它,对其进行了调整,将其粘合在一起,并使用 SumantraPDF 进行了测试。另请注意,此代码不是最高标准,但可以解决您的问题,并将作为一个可行的示例。

C++ 代码:(向下滚动查看 C# 代码)

#include <Windows.h>
#include <vector>

// 0 based index for preferred monitor
static const int PREFERRED_MONITOR = 1;  

struct ProcessWindowsInfo
{
    DWORD ProcessID;
    std::vector<HWND> Windows;

    ProcessWindowsInfo(DWORD const AProcessID)
        : ProcessID(AProcessID)
    {
    }
};

struct MonitorInfo
{
    HMONITOR hMonitor;
    RECT rect;
};


BOOL WINAPI EnumProcessWindowsProc(HWND hwnd, LPARAM lParam)
{
    ProcessWindowsInfo *info = reinterpret_cast<ProcessWindowsInfo*>(lParam);
    DWORD WindowProcessID;

    GetWindowThreadProcessId(hwnd, &WindowProcessID);

    if (WindowProcessID == info->ProcessID)
    {
        if (GetWindow(hwnd, GW_OWNER) == (HWND)0 && IsWindowVisible(hwnd))
        {
            info->Windows.push_back(hwnd);
        }
    }

    return true;
}


BOOL CALLBACK Monitorenumproc(HMONITOR hMonitor, HDC hdc, LPRECT lprect, LPARAM lParam)
{
    std::vector<MonitorInfo> *info = reinterpret_cast<std::vector<MonitorInfo>*>(lParam);

    MonitorInfo monitorInfo = { 0 };

    monitorInfo.hMonitor = hMonitor;
    monitorInfo.rect = *lprect;

    info->push_back(monitorInfo);
    return TRUE;
}


int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow)
{

    // NOTE: for now this code works only when the window is not already visible
    // could be easily modified to terminate existing process as required

    SHELLEXECUTEINFO info = { 0 };
    info.cbSize = sizeof(info);
    info.fMask = SEE_MASK_NOCLOSEPROCESS;
    info.lpFile = L"C:\\Program Files\\SumatraPDF\\SumatraPDF.exe"; 
    info.nShow = SW_SHOW;

    std::vector<MonitorInfo> connectedMonitors;

    // Get all available displays
    EnumDisplayMonitors(NULL, NULL, Monitorenumproc, reinterpret_cast<LPARAM>(&connectedMonitors));

    if (ShellExecuteEx(&info))
    {
        WaitForInputIdle(info.hProcess, INFINITE);

        ProcessWindowsInfo Info(GetProcessId(info.hProcess));

        // Go though all windows from that process
        EnumWindows((WNDENUMPROC)EnumProcessWindowsProc, reinterpret_cast<LPARAM>(&Info.ProcessID));

        if (Info.Windows.size() == 1)
        {
            // only if we got at most 1 window
            // NOTE: applications can have more than 1 top level window. But at least for SumtraPDF this works!

            if (connectedMonitors.size() >= PREFERRED_MONITOR)
            {
                // only move the window if we were able to successfully detect available monitors

                SetWindowPos(Info.Windows.at(0), 0, connectedMonitors.at(PREFERRED_MONITOR).rect.left, connectedMonitors.at(PREFERRED_MONITOR).rect.top, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
            }
        }

        CloseHandle(info.hProcess);
    }

    return 0;
}

在代码中强调我的一个 cmets。 此代码仅在相关进程尚未运行时才有效。否则,您可以根据自己的要求调整代码。

更新:在下面添加了 C# 代码,因为我意识到 OP 更喜欢 C#。此代码还包含终止逻辑。

C# 代码:

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

private const int SWP_NOSIZE = 0x0001;
private const int SWP_NOZORDER = 0x0004;

private const int PREFERRED_MONITOR = 1;

static void Main(string[] args)
{

    // NOTE: you will have to reference System.Windows.Forms and System.Drawing (or 
    // equivalent WPF assemblies) for Screen and Rectangle

    // Terminate existing SumatraPDF process, else we will not get the MainWindowHandle by following method.
    List<Process> existingProcesses = Process.GetProcessesByName("SumatraPDF").ToList();

    foreach (var existingProcess in existingProcesses)
    {
        // Ouch! Ruthlessly kill the existing SumatraPDF instances
        existingProcess.Kill();
    }

    // Start the new instance of SumantraPDF

    Process process = Process.Start(@"C:\Program Files\SumatraPDF\SumatraPDF.exe");

    // wait max 5 seconds for process to be active
    process.WaitForInputIdle(5000);


    if (Screen.AllScreens.Length >= PREFERRED_MONITOR)
    {
        SetWindowPos(process.MainWindowHandle,
            IntPtr.Zero,
            Screen.AllScreens[PREFERRED_MONITOR].WorkingArea.Left,
            Screen.AllScreens[PREFERRED_MONITOR].WorkingArea.Top,
            0, 0, SWP_NOSIZE | SWP_NOZORDER);
    }
}

【讨论】:

    【解决方案2】:

    SEE_MASK_HMONITOR 只是一个请求。应用程序可以选择自己的窗口位置。 SEE_MASK_HMONITOR 仅在执行的应用程序依赖于默认窗口放置时才有效,即它使用 CW_USE­DEFAULT 创建其第一个顶级窗口

    所以你想要的通常是不可能的。如果您不控制启动的应用程序,您的代码将尽可能好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-09
      • 2011-03-21
      • 2016-01-21
      • 2011-03-27
      • 1970-01-01
      • 2013-02-05
      • 1970-01-01
      • 2019-12-02
      相关资源
      最近更新 更多