Windows 程序启动在指定屏幕

Windows 在多屏幕的情况下,EnumDisplayMonitors() 枚举所有显示器,通过 GetMonitorInfo() 可以取得指定显示器的相关信息,如物理显示区大小等。MonitorInfo 结构中保存着相应显示器的相关信息,如坐标、是否为主显示器等。该结构体中有个 dwFlags 变量表示该显示器是否为主显示器,当值为 MONITORINFOF_PRIMARY 时就说明是主显示器,根据这个值就可以区分主显示器和副显示器。
示例代码如下:

#include <Windows.h>
#include <iostream>
#include <vector>
 
BOOL CALLBACK EnumMonitor(HMONITOR handle, HDC hdc, LPRECT rect, LPARAM param) {
	std::vector<MONITORINFO> *list = (std::vector<MONITORINFO>*)param;
	MONITORINFO mi;
	mi.cbSize = sizeof(mi);
	GetMonitorInfo(handle, &mi);
	list->push_back(mi);
	return true;
}

int main(void) {
	// 获取当前显示器的数目
	int numbers = GetSystemMetrics(SM_CMONITORS);
	std::cout << "The current number of screens is:" << numbers << "\r\n" << std::endl;
	
	std::vector<MONITORINFO> monitor_list;
	EnumDisplayMonitors(NULL, NULL, EnumMonitor, (LPARAM)&monitor_list);
	for (size_t i = 0; i < monitor_list.size(); ++i) {
		RECT rect = monitor_list[i].rcMonitor;
		std::cout << "MONITORINFOF_PRIMARY:" << monitor_list[i].dwFlags << std::endl;
		std::cout << "left:" << rect.left << ",right:" << rect.right << ",bottom:" << rect.bottom << ",top:" << rect.top << std::endl;
		std::cout << "width:" << (rect.right - rect.left) << std::endl;
		std::cout << "height:" << (rect.bottom - rect.top) << "\r\n" << std::endl;
		if(monitor_list[i].dwFlags == 0){
			HWND hwnd = GetForegroundWindow();
			LONG last_style  = GetWindowLong(hwnd,GWL_STYLE);
			//设置全屏
			SetWindowLong(hwnd,GWL_STYLE,last_style | WS_POPUP | WS_MAXIMIZE);
			//移动到指定屏幕
			MoveWindow(hwnd, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, TRUE);
		}
	}
	getchar();
	return 0;
}

运行结果如下:
运行结果
移动窗口到指定位置的接口为:

BOOL MoveWindow( HWND hWnd,int x, int y, int nWidth, int nHeight,BOOL bRepaint = TRUE);

参数 hWnd 表示窗口的句柄;
参数 x,y 表示窗口的左上角起点坐标;
参数 nWidth,nHeight 表示窗口的高度和宽度;
最后一个参数 bRepaint 表示是否立即重绘。为 true 时系统会立即发送 WM_PAINT 到窗口程序(会调用UpdateWindow()函数),为 false 时则不会发生任何类型的重绘操作。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ByteSaid

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值