在多显示器的Windows工作场景下,有时候需要把某个程序固定到指定的显示器上,可是系统并没有提供简单的方法,本文将介绍使用C++代码和批处理文件实现将指定程序窗口固定到指定显示屏的方法。
准备工作
首先需要准备以下软件和库:
- Visual Studio 2017(或其他C++ IDE)
- WinAPI
编写程序
在IDE中创建一个新的Console Application项目,然后按照以下方式编写C++程序:
#include <Windows.h>
#include <iostream>
#include <vector>
BOOL CALLBACK MonitorEnumProc(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData)
{
std::vector<MONITORINFOEX>* monitors = reinterpret_cast<std::vector<MONITORINFOEX>*>(dwData);
// 获取显示器信息
MONITORINFOEX monitorInfo = {};
monitorInfo.cbSize = sizeof(MONITORINFOEX);
if (GetMonitorInfo(hMonitor, &monitorInfo))
{
monitors->push_back(monitorInfo);
}
return TRUE;
}
int main(int argc, char **argv)
{
// 接收到的参数格式错误直接返回
if (argc < 3 || argc > 4) {
std::cout << "参数错误" << std::endl;
//终止返回错误码
std