Win32 窗口篇(1)

 

例子来自某书…
目标:会用就OK,达到熟悉Win32 API的目的.

1.1 如何通过HWND获得CWnd指针

CWnd::GetSafeHwnd:

Returns the window handle for a window. Returns NULL if the CWnd is not attached to a window or if it is used with a NULL CWnd pointer.

CWnd::FromHandle:
Returns a pointer to a CWnd object when given a handle to a window. If a CWnd object is not attached to the handle, a temporary CWnd object is created and attached.

//获得当前窗口的句柄
HWND hWnd = GetSafeHwnd();

//通过HWND获得CWnd指针
CWnd* pWnd = CWnd::FromHandle(hWnd);

1.2 如何获得应用程序主窗口的指针

使用AfxGetApp获取应用程序指针

//获得应用程序指针
CDemoApp* pApp = (CDemoApp*)AfxGetApp();

//获得主窗口指针
CWnd* pMainWnd = pApp->m_pMainWnd;

1.3 如何获得指定点的窗口

如下代码:

void CDemoDlg::OnMouseMove(UINT nFlags, CPoint point) 
{
    //获得指定点的窗口
    CWnd* pWnd = WindowFromPoint(point);
    
    if (pWnd != NULL)
    {
         if (IsChild(pWnd))
         {
            CString strText = _T("");
            pWnd->GetWindowText(strText);
            SetWindowText(strText);
        }
    }

    CDialog::OnMouseMove(nFlags, point);
}

方法1:WindowFromPoint

A pointer to the window object in which the point lies. It is NULL if no window exists at the given point. The returned pointer may be temporary and should not be stored for later use.
方法2:IsChild(MFC中每个控件都是一个窗体)
Determines whether the specified window is a child window.
方法3:GetWindowText和SetWindowText
获取和设置窗体标题

如下效果:
image

当鼠标经过TextBox,则IsChild判断为True,在TextBox范围内鼠标移动则更改窗体标题

1.4 如何最大化和最小化窗口

示例如下:

void CDemoDlg::OnTest1() 
{
    //最大化窗口
    SendMessage(WM_SYSCOMMAND, SC_MAXIMIZE, 0);    
}

void CDemoDlg::OnTest2() 
{
    //最小化窗口
    SendMessage(WM_SYSCOMMAND, SC_MINIMIZE, 0);    
}

void CDemoDlg::OnTest3() 
{
    //恢复窗口
    SendMessage(WM_SYSCOMMAND, SC_RESTORE, 0);    
}

WM_SYSCOMMAND 为系统内置的命令,只需要用SendMessage发送预先设置的命令就可以了

1.5 如何关闭窗口

同上,用SendMessage发送预先设置的命令

void CDemoDlg::OnTest() 
{
    //关闭窗口
    
    SendMessage(WM_SYSCOMMAND,SC_CLOSE, 0);
}

或者直接发送WM_CLOSE

void CDemoDlg::OnTest() 
{
    //关闭窗口

    SendMessage(WM_CLOSE, 0, 0);
}

关闭前确认:

void CDemoDlg::OnClose() 
{
    //判断是否关闭
    if (IDYES == MessageBox(_T("是否关闭窗口?"), NULL, MB_YESNO))
    {
        CDialog::OnClose();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值