如何以编程方式在Windows 10的特定监视器上启动应用程序?

时间:2018-08-13 12:55:10

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

我想编写一个有时需要在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;
}

2 个答案:

答案 0 :(得分:3)

正如其他人所建议的,这是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;
}

强调我在代码中的注释之一。 仅当相关进程尚未运行时,此代码才有效。您可以按照自己的要求调整代码。

更新:由于我意识到OP更喜欢C#,因此在下面添加了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);
    }
}

答案 1 :(得分:2)

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

创建其第一个顶级窗口

因此,通常无法满足您的需求。如果您不控制启动的应用程序,则您的代码将尽可能地好。