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创建正则表达式对象的两种方法
  2. Dr.Batcher 2.3.3 注册码
  3. Unicode中的方框绘制字符
  4. VBS 获取外网 IP 并发送到指定邮箱
  5. 效率低下的Split函数,用VBS的人你伤不起

留下回复