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



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

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

首选语言是 C# 和 Java,但任何帮助都值得赞赏。

编辑

我尝试直接在C++代码中使用 IInspectable 建议的ShellExecuteExW功能,但它不起作用,因为应用程序出现在主显示器上。我肯定犯了一个错误,因为我绝对是 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;
}

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

此外,您至少不能依赖苏门答腊PDF的默认窗口放置,因为它肯定不使用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;
}

强调我在代码中的一条评论。仅当相关进程尚未运行时,此代码才有效。否则,您可以根据需要调整代码。

更新:在下面添加了 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 FilesSumatraPDFSumatraPDF.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);
}
}

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

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

最新更新