多顯示器環境中移動視窗到指定的顯示器
阿新 • • 發佈:2018-12-27
//顯示器資訊結構體 typedef struct _tagMyMonitorInfo_t { HMONITOR hMonitor; MONITORINFOEX info; _tagMyMonitorInfo_t() { ZeroMemory(this, sizeof(*this)); } }MYMONITORINFO, *LPMYMONITORINFO; CArray <MYMONITORINFO> m_MyMonitorInfo; //EnumDisplayMonitors 回撥函式 BOOL CALLBACK MonitorEnumProc(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) { MYMONITORINFO mInfo; mInfo.hMonitor = hMonitor; mInfo.info.cbSize = sizeof(mInfo.info); GetMonitorInfo(hMonitor, &mInfo.info); m_MyMonitorInfo.Add(mInfo); return TRUE; } int MoveWindow2Monitor( int iMonitorIndex, //顯示器索引0,1,2,etc HWND hWnd, //視窗指標 int x=0, int y=0, //視窗左上角座標偏移 int cx=0, int cy=0 //視窗尺寸 (0時不改變) ) { int iRet = 0; do { //視窗控制代碼有效? if(!IsWindow(hWnd)) { TRACE(_T("Invalid window handle\n")); iRet = -1; break; } //列舉顯示器 m_MyMonitorInfo.RemoveAll(); if(!EnumDisplayMonitors(NULL, NULL, MonitorEnumProc, NULL)) { TRACE(_T("EnumDisplayMonitors failed %u\n"), GetLastError()); iRet = -2; break; } //顯示器索引是否正常? if(iMonitorIndex >= /*GetSystemMetrics(SM_CMONITORS)*/ m_MyMonitorInfo.GetSize()) { TRACE(_T("Out of Monitor ranges\n")); iRet = -3; break; } //工作區域座標 RECT rcWork = m_MyMonitorInfo[iMonitorIndex].info.rcWork; //左上角座標 x += rcWork.left; y += rcWork.top; //尺寸 RECT rcWnd; GetWindowRect(hWnd, &rcWnd); if(cx == 0) cx = rcWnd.right - rcWnd.left; if(cy == 0) cy = rcWnd.bottom - rcWnd.top; //位置限制 { } //移動視窗 if(!SetWindowPos(hWnd, NULL, x, y, cx, cy, SWP_FRAMECHANGED|SWP_NOZORDER)) { TRACE(_T("SetWindowPos failed %u"), GetLastError()); iRet = -4; break; } iRet = TRUE; }while(0); return iRet; }
//測試函式
void CDlg2Dlg::OnButton1()
{
// TODO: Add your control notification handler code here
//移動視窗到第二個顯示器上
MoveWindow2Monitor(1, m_hWnd);
}