gpt4 book ai didi

c - 如果在注册窗口类时已经提供了 hInstance,为什么 CreateWindow() 将 hInstance 作为参数?

转载 作者:太空狗 更新时间:2023-10-29 15:19:54 25 4
gpt4 key购买 nike

注册窗口类时需要填写WNDCLASS结构,它有一个 hInstance领域:

typedef struct {
UINT style;
WNDPROC lpfnWndProc;
int cbClsExtra;
int cbWndExtra;
HINSTANCE hInstance;
HICON hIcon;
HCURSOR hCursor;
HBRUSH hbrBackground;
LPCTSTR lpszMenuName;
LPCTSTR lpszClassName;
} WNDCLASS

然后,使用 CreateWindow() 创建窗口它接受这些参数:

HWND CreateWindow(          
LPCTSTR lpClassName,
LPCTSTR lpWindowName,
DWORD dwStyle,
int x,
int y,
int nWidth,
int nHeight,
HWND hWndParent,
HMENU hMenu,
HINSTANCE hInstance,
LPVOID lpParam
);

  • 如果hInstance提供了 WNDCLASS注册类(class)时,为什么需要提供 hInstanceCreateWindow() ?

  • hInstance提供给WNDCLASS应该与 hInstance 相同提供给CreateWindow() ?

  • 如果WNDCLASS hInstanceCreateWindow() hInstance不同,它们是什么意思?


这是一个演示类注册/窗口创建的示例程序:

#include <windows.h>

LPSTR szClassName = "MyClass";
HINSTANCE hInstance;
LRESULT CALLBACK MyWndProc(HWND, UINT, WPARAM, LPARAM);

int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInstance, LPSTR szCmdLine, int iCmdShow)
{
WNDCLASS wnd;
MSG msg;
HWND hwnd;

hInstance = hInst;

wnd.style = CS_HREDRAW | CS_VREDRAW; //we will explain this later
wnd.lpfnWndProc = MyWndProc;
wnd.cbClsExtra = 0;
wnd.cbWndExtra = 0;
wnd.hInstance = hInstance;
wnd.hIcon = LoadIcon(NULL, IDI_APPLICATION); //default icon
wnd.hCursor = LoadCursor(NULL, IDC_ARROW); //default arrow mouse cursor
wnd.hbrBackground = (HBRUSH)(COLOR_BACKGROUND+1);
wnd.lpszMenuName = NULL; //no menu
wnd.lpszClassName = szClassName;

if(!RegisterClass(&wnd)) //register the WNDCLASS
{
MessageBox(NULL, "This Program Requires Windows NT",
"Error", MB_OK);
return 0;
}

hwnd = CreateWindow(szClassName,
"Window Title",
WS_OVERLAPPEDWINDOW, //basic window style
CW_USEDEFAULT,
CW_USEDEFAULT, //set starting point to default value
CW_USEDEFAULT,
CW_USEDEFAULT, //set all the dimensions to default value
NULL, //no parent window
NULL, //no menu
hInstance,
NULL); //no parameters to pass
ShowWindow(hwnd, iCmdShow); //display the window on the screen
UpdateWindow(hwnd); //make sure the window is updated correctly

while(GetMessage(&msg, NULL, 0, 0)) //message loop
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}

LRESULT CALLBACK MyWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch(msg)
{
case WM_DESTROY:
PostQuitMessage(0);
return 0;
}
return DefWindowProc(hwnd, msg, wParam, lParam);
}

最佳答案

注册窗口类时,它可以是全局的(设置了 CS_GLOBALCLASS 样式),也可以是注册它的模块的本地类。对于全局类,类名必须是唯一的,但对于模块本地类,类名可能会发生冲突——没有什么可以阻止两个 DLL 注册同名的窗口类,并且一个可执行文件可以加载这两个 DLL。

因此,您需要告诉 CreateWindow 函数您要使用指定类的哪个模块实例来创建窗口。

关于c - 如果在注册窗口类时已经提供了 hInstance,为什么 CreateWindow() 将 hInstance 作为参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20140117/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com