自定义的窗口居中函数--CentreWindow

本文提供了两种实现窗口居中显示的方法。第一种方法通过获取窗口和父窗口的位置及大小,计算出居中位置并调用MoveWindow函数实现;第二种方法则获取工作区大小和窗口大小,确保窗口不会超出工作区范围,并使用SetWindowPos函数完成居中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 
自定义函数一
BOOL CENTER_WINDOW(HWND hWnd, HWND hParent) // 自定义的窗口居中函数
{
    if (!IsWindow(hWnd))
        return FALSE;
    if (!IsWindow(hParent) || 0 == hParent)
        hParent = GetDesktopWindow();
    RECT rcWnd;
    GetWindowRect(hWnd, &rcWnd);
    RECT rcParent;
    GetWindowRect(hParent, &rcParent);
    POINT ptNew;
    int nWidth;
    int nHeight;
    int nParentWidth;
    int nParentHeight;
    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; 

    // Find how large the desktop work area is 
    SystemParametersInfo(SPI_GETWORKAREA, 0, &workrect, 0); 
    int workwidth = workrect.right - workrect.left; 
    int workheight = workrect.bottom - workrect.top; 

    // And how big the window is 
    GetWindowRect(hwnd, &winrect); 
    int winwidth = winrect.right - winrect.left; 
    int winheight = winrect.bottom - winrect.top; 

    // Make sure it's not bigger than the work area 
    winwidth = min(winwidth, workwidth); 
    winheight = min(winheight, workheight); 

    // Now centre it 
    SetWindowPos(hwnd, 
                HWND_TOP, 
                workrect.left + (workwidth-winwidth) / 2, 
                workrect.top + (workheight-winheight) / 2, 
                winwidth, winheight, 
                SWP_SHOWWINDOW); 
    SetForegroundWindow(hwnd); 
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值