#2
BCCN_xkx2015-09-10 17:48
下面是全部的代码:
有兴趣的朋友复制运行一下,看看结果。 #include <stdio.h> #include <windows.h> LRESULT CALLBACK WinSunPROC(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_CHAR: //字符事件 { char szChar[20]; sprintf(szChar, "char is %d", wParam); MessageBox(hwnd, szChar, "hh", 0); }break; case WM_NCLBUTTONDOWN: //鼠标左键按下事件 { MessageBox(hwnd, "mouse clicked", "hh", 0); HDC hdc; hdc = GetDC(hwnd); TextOut(hdc, 0, 50, "鼠标左键", strlen("鼠标左键")); ReleaseDC(hwnd, hdc); }break; case WM_PAINT: //窗口重绘事件 { HDC hDc; PAINTSTRUCT ps; hDc = BeginPaint(hwnd, &ps); TextOut(hDc, 0, 0, "第一课", strlen("第一课")); EndPaint(hwnd, &ps); }break; case WM_CLOSE: //窗口关闭事件 { if (IDYES == MessageBox(hwnd, "是否真的结束?", "hh", MB_YESNO)) { DestroyWindow(hwnd); //销毁该窗口 } }break; case WM_DESTROY: //窗口销毁事件 { PostQuitMessage(0); //往本线程的消息队列中发送一个。。。 }break; default: return DefWindowProc(hwnd, uMsg, wParam, lParam); } return 0; } int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow ) { WNDCLASS wndcls; wndcls.cbClsExtra = 0; wndcls.cbClsExtra = 0; wndcls.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH); wndcls.hCursor = LoadCursor(NULL,IDC_CROSS); wndcls.hIcon = LoadIcon(NULL,IDI_APPLICATION); wndcls.hInstance = hInstance; wndcls.lpfnWndProc = WinSunPROC; wndcls.lpszClassName = "xu"; wndcls.lpszMenuName = NULL; wndcls.style = CS_HREDRAW | CS_VREDRAW; if (RegisterClass(&wndcls) == 0) { DWORD dw = GetLastError(); //87:参数无效 MessageBox(NULL, TEXT("窗口类注册失败!"), TEXT("提示"), MB_OK); return 1; } HWND hwnd; hwnd = CreateWindow("xu", "测试", WS_OVERLAPPEDWINDOW, 10, 10, 600, 400, NULL, NULL, hInstance,NULL); if (hwnd) { ShowWindow(hwnd, SW_SHOWNORMAL); } else { DWORD dw = GetLastError(); //1407 :找不到窗口类别。 MessageBox(NULL, TEXT("创建窗口失败!"), TEXT("提示"), MB_OK); UnregisterClass("xu", hInstance); //移除注册 return 1; } MSG msg; while (GetMessage(&msg,NULL,0,0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return 0; } |
先在这给各位问声好!
接下来我们来讨论一个问题,我刚开始学习vc++,按照书上的代码,写出了我的第一个程序,可是运行不对,具体就是窗口类注册失败,代码如下:
int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nCmdShow)
{
...
WNDCLASS wndcls;
wndcls.cbClsExtra = 0;
wndcls.cbClsExtra = 0;
wndcls.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
wndcls.hCursor = LoadCursor(NULL,IDC_CROSS);
wndcls.hIcon = LoadIcon(NULL,IDI_APPLICATION);
wndcls.hInstance = hInstance;
wndcls.lpfnWndProc = WinSunPROC;
wndcls.lpszClassName = "xu";
wndcls.lpszMenuName = NULL;
wndcls.style = CS_HREDRAW | CS_VREDRAW;
if (RegisterClass(&wndcls) == 0)
{
DWORD dw = GetLastError(); //87:参数无效
MessageBox(NULL, TEXT("窗口类注册失败!"), TEXT("提示"), MB_OK);
return 1;
}
...
}
得到的错误代码为87,说是无效的参数,可是我检查过,结构体的参数初始化没错啊~~~,求大神解答。
ps.win10 和 win7 系统都试过了,结果一样。
ps.代码参考的是孙鑫的vc++书上的。