win32创建一个窗口,创建一个菜单“打开",当点击“打开”菜单项时,弹出非模式对话框,标题为“非模式对话框”,该对话框有一编辑框和一按钮确定,
时间: 2024-04-29 13:21:05 浏览: 55
以下是示例代码:
```c++
#include <Windows.h>
// 声明全局变量
HINSTANCE hInst;
HWND hMainWnd;
// 声明函数
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
BOOL CALLBACK DlgProc(HWND, UINT, WPARAM, LPARAM);
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nCmdShow)
{
// 初始化全局变量
hInst = hInstance;
// 创建主窗口
WNDCLASSEX wcx = { sizeof(wcx) };
wcx.style = CS_HREDRAW | CS_VREDRAW;
wcx.lpfnWndProc = WndProc;
wcx.hInstance = hInst;
wcx.hCursor = LoadCursor(NULL, IDC_ARROW);
wcx.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wcx.lpszClassName = TEXT("MyWindowClass");
RegisterClassEx(&wcx);
hMainWnd = CreateWindow(TEXT("MyWindowClass"), TEXT("My Window"),
WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT,
CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInst, NULL);
// 创建菜单
HMENU hMenu = CreateMenu();
AppendMenu(hMenu, MF_STRING, ID_FILE_OPEN, TEXT("打开"));
// 将菜单关联到主窗口
SetMenu(hMainWnd, hMenu);
// 显示主窗口
ShowWindow(hMainWnd, nCmdShow);
UpdateWindow(hMainWnd);
// 进入消息循环
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return (int)msg.wParam;
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_COMMAND:
switch (LOWORD(wParam))
{
case ID_FILE_OPEN:
// 弹出非模式对话框
DialogBox(hInst, MAKEINTRESOURCE(IDD_MYDIALOG), hWnd, DlgProc);
break;
}
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
BOOL CALLBACK DlgProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_INITDIALOG:
SetWindowText(hDlg, TEXT("非模式对话框"));
return TRUE;
case WM_COMMAND:
switch (LOWORD(wParam))
{
case IDOK:
EndDialog(hDlg, IDOK);
break;
case IDCANCEL:
EndDialog(hDlg, IDCANCEL);
break;
}
break;
default:
return FALSE;
}
return TRUE;
}
```
其中,`ID_FILE_OPEN`和`IDD_MYDIALOG`是自定义的标识符,需要在资源文件中定义:
```rc
#include "resource.h"
ID_FILE_OPEN MENUITEM "打开"
IDC_EDIT1 EDITTEXT 10, 10, 150, 20, WS_BORDER | WS_TABSTOP | ES_AUTOHSCROLL
IDC_BUTTON1 PUSHBUTTON "确定", 10, 40, 75, 25, WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON
IDD_MYDIALOG DIALOGEX 0, 0, 200, 100, WS_CAPTION | WS_SYSMENU | DS_MODALFRAME | DS_SETFONT, 0, 0, "My Dialog", 9, "MS Shell Dlg", 0
{
CONTROL "编辑框", IDC_EDIT1, "EDIT", ES_LEFT | ES_AUTOHSCROLL | WS_CHILD | WS_VISIBLE | WS_BORDER | WS_TABSTOP, 10, 10, 150, 20
CONTROL "确定", IDC_BUTTON1, "BUTTON", BS_PUSHBUTTON | WS_CHILD | WS_VISIBLE | WS_TABSTOP, 10, 40, 75, 25
CONTROL "取消", IDCANCEL, "BUTTON", BS_PUSHBUTTON | WS_CHILD | WS_VISIBLE | WS_TABSTOP, 95, 40, 75, 25
}
```
最后,需要在代码中包含资源文件头文件:
```c++
#include "resource.h"
```
阅读全文