Win32-Application的窗口和对话框


Win32 Application,没有基于MFC的类库,而是直接调用C++接口来编程。

 

一、弹出消息窗口

(1)最简单的,在当前窗口中弹出新窗口。新窗口只有“YES”按钮。

int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow)
{
    MessageBox(NULL, "我的Win32程序", "HelloWorld", MB_OK);
    return 0;
}

 

(2)获取已经打开的窗口,并在该窗口中弹出新窗口,而且新窗口有“YES/NO/CANCEL”按钮,可以捕获该返回值。

int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow)
{
     // TODO: Place code here.
    HWND hWnd = ::FindWindow(NULL, "无标题 - 记事本");
    int nRet = MessageBox(hWnd, "我的Win32程序", "HelloWorld", MB_YESNOCANCEL|MB_ICONQUESTION);
    if(IDYES == nRet){
        MessageBox(hWnd, "你点击了\"是\"按钮", "返回值", 0);    
    }
    else if(IDNO == nRet){
        MessageBox(hWnd, "你点击了\"否\"按钮", "返回值", 0);    
    }
    else{
        MessageBox(hWnd, "你点击了\"取消\"按钮", "返回值", 0);    
    }

    return 0;
}

 

二、对话框

(1)通过DialogBox新增一个对话框,并设置对话框的消息处理回调函数MainProc,接收对话框的返回值并做相应处理:

int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow)
{
    int nRet;
    nRet = DialogBox(hInstance, (LPCSTR)IDD_DIALOG1, NULL, MainProc);
    if(IDCANCEL == nRet){
        MessageBox(NULL, "CANCEL", "返回值", 0);
        return -1;
    }

    return 0;
}

 

 

回调函数中,通过GetDlgItemInt获取对话框的输入整型值、通过SetDlgItemInt设置对话框的输出整型值(如果是字符串,Int改为Text),通过EndDialog关闭对话框,并返回不同的返回值:

BOOL CALLBACK MainProc(
    HWND hwndDlg,
    UINT uMsg,
    WPARAM wParam,
    LPARAM lParam
)
{
    OutputDebugString("测试运行状态\n");

    if(WM_COMMAND == uMsg)
    {
        if(LOWORD(wParam) == IDCANCEL){
            EndDialog(hwndDlg, IDCANCEL);
            return IDCANCEL;
        }
        else if(LOWORD(wParam) == IDOK){
            int nLeft = GetDlgItemInt(hwndDlg, IDC_LEFT, NULL, TRUE);
            int nRight = GetDlgItemInt(hwndDlg, IDC_RIGHT, NULL, TRUE);
            int nResult = nLeft + nRight;
            SetDlgItemInt(hwndDlg, IDC_RESULT, nResult, TRUE);
        }
    }

    return FALSE;
}

 

备注:

  对话框的资源属性,可以编辑弹出位置、对其方式、显示效果、是否可编辑等等。

  Ctrl+D,可以编辑对话框的焦点顺序。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM