在开发“518抽奖软件”的时候,需要用到窗口化、全屏化、移到扩展屏的功能。 网上找的代码都不够全面,有时候会被任务栏挡住。所以自己写了一个代码,下面的代码是商业产品上正式使用的代码,比一般网上随便写的代码好的多,各种情况测试都通过。
窗口创建阶段的源码
if (m_wndPos.wndMode == WNDMODE_WINDOW)
m_hMain = CreateWindow(WNDCLASS_NAME, g_title, WS_POPUP, m_wndPos.x, m_wndPos.y, m_wndPos.w, m_wndPos.h, NULL, NULL, m_hInst, NULL);
else
m_hMain = CreateWindow(WNDCLASS_NAME, g_title, WS_POPUP, 0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN), NULL, NULL, m_hInst, NULL);
ShowWindow (m_hMain, SW_SHOW);
UpdateWindow (m_hMain);
SetWindowPos(m_hMain, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
窗口消息里的源码
case WM_ACTIVATEAPP:
if ((BOOL)wParam) {
SetWindowPos(hWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
}
else {
SetWindowPos(hWnd, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE);
PostMessage(hWnd, WM_APP_BRINGTOTOP, 0, 0);
}
break;
case WM_APP_BRINGTOTOP:
BringWindowToTop(GetForegroundWindow());
break;
case WM_SHOWWINDOW:
if (!(BOOL)wParam) return DefWindowProc(hWnd, message, wParam, lParam);
else SetWindowPos(hWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
break;
case WM_LBUTTONDOWN:
BringWindowToTop(g_app.m_hMain);
break;
窗口化、全屏化、扩展屏切换的源码
wndPos_t& wp = g_app.m_wndPos;
int cx = GetSystemMetrics(SM_CXSCREEN);
int cy = GetSystemMetrics(SM_CYSCREEN);
if (wmId == IDM_window)
{
if (wp.wndMode == WNDMODE_EXSCRN) SetCursorPos(cx - 1, cy - 1); //鼠标移回主窗口
wp.wndMode = WNDMODE_WINDOW;
MoveWindow(g_app.m_hMain, wp.x, wp.y, wp.w, wp.h, TRUE);
Sleep(16);
BringWindowToTop(g_app.m_hMain);
}
else if (wmId == IDM_fuscrn)
{
if (wp.wndMode == WNDMODE_EXSCRN) SetCursorPos(cx - 1, cy - 1); //鼠标移到扩展屏
wp.wndMode = WINMODE_FUSCRN;
MoveWindow(g_app.m_hMain, 0, 0, cx, cy, TRUE);
}
else if (wmId == IDM_exscrn)
{
RECT rc;
if (!g_app.get_exscrn(rc)) MessageBox(g_app.m_hMain, L"无扩展屏", g_title, MB_OK | MB_ICONWARNING);
else
{
wp.wndMode = WNDMODE_EXSCRN;
MoveWindow(g_app.m_hMain, rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top, TRUE);
SetCursorPos(rc.right - 1, rc.bottom - 1);
}
}
获得第二屏(扩展屏)位置的源码
BOOL Tapp::get_exscrn(RECT& rcExscrn)
{
RECT rc = { 0 };
EnumDisplayMonitors(NULL, NULL, Callback_enumMonitors, (LPARAM)&rc);
if (rc.left == 0 && rc.top == 0 && rc.right == 0 && rc.bottom == 0) return FALSE;
rcExscrn = rc;
return TRUE;
}
static BOOL CALLBACK Callback_enumMonitors(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData)
{
RECT* rc = (RECT*)dwData;
MONITORINFO mi = { 0 };
mi.cbSize = sizeof(MONITORINFO);
GetMonitorInfo(hMonitor, &mi);
if (mi.dwFlags != MONITORINFOF_PRIMARY)
{
*rc = mi.rcMonitor;
return FALSE;
}
return TRUE;
}