SDK编程中的窗口居中

标签: , , ,

MFC程序中调用CWnd::CenterWindow就可以实现窗口居中,但是纯SDK编程中没有CenterWindow这个函数,需要自定义一个。Google到一个比较好的实现。

自定义函数一:

BOOL CENTER_WINDOW(HWND hWnd, HWND hParent)
{
    RECT rcWnd, rcParent;
    POINT ptNew;
    int nWidth;
    int nHeight;
    int nParentWidth;
    int nParentHeight;

    if (!IsWindow(hWnd))
        return FALSE;

    if (!IsWindow(hParent) || 0 == hParent)
        hParent = GetDesktopWindow();
    
    GetWindowRect(hWnd, &rcWnd);
    GetWindowRect(hParent, &rcParent);
       
    nWidth = rcWnd.right - rcWnd.left;
    nHeight = rcWnd.bottom - rcWnd.top;
    nParentWidth = rcParent.right - rcParent.left;
    nParentHeight = rcParent.bottom - rcParent.top;
    ptNew.x = rcParent.left + (nParentWidth - nWidth) / 2;
    ptNew.y = rcParent.top + (nParentHeight - nHeight) / 2;
    
    return MoveWindow(hWnd, ptNew.x, ptNew.y, nWidth, nHeight, TRUE);
}

自定义函数二:

void CentreWindow(HWND hwnd)
{
	RECT winrect, workrect;
	int workwidth, workheight, winwidth, winheight;

	SystemParametersInfo(SPI_GETWORKAREA, 0, &workrect, 0);
	workwidth = workrect.right - workrect.left;
	workheight = workrect.bottom - workrect.top;

	GetWindowRect(hwnd, &winrect);
	winwidth = winrect.right - winrect.left;
	winheight = winrect.bottom - winrect.top;

	winwidth = min(winwidth, workwidth);
	winheight = min(winheight, workheight);

	SetWindowPos(hwnd, HWND_TOP,
		workrect.left + (workwidth-winwidth) / 2,
		workrect.top + (workheight-winheight) / 2,
		winwidth, winheight,
		SWP_SHOWWINDOW);
	SetForegroundWindow(hwnd);
}

参考链接:自定义的窗口居中函数–CentreWindow

赞赏

微信赞赏支付宝赞赏

随机文章:

  1. VBS正则表达式对象的MultiLine属性
  2. 使用Image Generator (Image Builder)生成OpenWrt固件
  3. MSDN 6.0 简体中文完全版下载
  4. 文件属性中“大小”和“占用空间”的区别
  5. VBS显示桌面

留下回复