Win32 API 多线程编程示例 - 窗口版
生活随笔
收集整理的這篇文章主要介紹了
Win32 API 多线程编程示例 - 窗口版
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
網上有一些Win32 多線程編程示例,多是控制臺版本;下面哥作一個窗口版本;
/*-------------------------------------------------bobo, 2020-------------------------------------------------*/#include <windows.h> #include <windowsx.h>LRESULT CALLBACK WndProc (HWND, UINT, WPARAM, LPARAM) ; DWORD WINAPI ThreadProc1(HDC); DWORD WINAPI ThreadProc2(HDC);int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance,PSTR szCmdLine, int iCmdShow) {static TCHAR szAppName[] = TEXT ("ThreadDemo") ;HWND hwnd ;MSG msg ;WNDCLASS wndclass ;wndclass.style = CS_HREDRAW | CS_VREDRAW ;wndclass.lpfnWndProc = WndProc ;wndclass.cbClsExtra = 0 ;wndclass.cbWndExtra = 0 ;wndclass.hInstance = hInstance ;wndclass.hIcon = LoadIcon (NULL, IDI_APPLICATION) ;wndclass.hCursor = LoadCursor (NULL, IDC_ARROW) ;wndclass.hbrBackground = (HBRUSH) GetStockObject (WHITE_BRUSH) ;wndclass.lpszMenuName = NULL ;wndclass.lpszClassName = szAppName ;if (!RegisterClass (&wndclass)){MessageBox (NULL, TEXT ("Program requires Windows NT!"), szAppName, MB_ICONERROR) ;return 0 ;}hwnd = CreateWindow (szAppName, TEXT ("ThreadDemo"),WS_OVERLAPPEDWINDOW,CW_USEDEFAULT, CW_USEDEFAULT,CW_USEDEFAULT, CW_USEDEFAULT,NULL, NULL, hInstance, NULL) ;ShowWindow (hwnd, iCmdShow) ;UpdateWindow (hwnd) ;while (GetMessage (&msg, NULL, 0, 0)){TranslateMessage (&msg) ;DispatchMessage (&msg) ;}return msg.wParam ; }LRESULT CALLBACK WndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {HDC hdc ;int x, y ;PAINTSTRUCT ps ;RECT rect ;char buffer[65];HANDLE hThread1, hThread2;switch (message){case WM_CREATE:return 0;case WM_SIZE :return 0 ;case WM_RBUTTONDOWN :return 0;case WM_LBUTTONDOWN :hdc = GetDC(hwnd);hThread1 = CreateThread(NULL, NULL, ThreadProc1, hdc, NULL, NULL);hdc = GetDC(hwnd);hThread2 = CreateThread(NULL, NULL, ThreadProc2, hdc, NULL, NULL);WaitForSingleObject(hThread1, INFINITE);WaitForSingleObject(hThread2, INFINITE);TextOut(hdc, 500, 20, TEXT("我是主線程"), 5);return 0 ;case WM_PAINT :hdc = BeginPaint (hwnd, &ps) ;EndPaint (hwnd, &ps) ;return 0 ;case WM_DESTROY :PostQuitMessage (0) ;return 0 ;}return DefWindowProc (hwnd, message, wParam, lParam) ; }DWORD WINAPI ThreadProc1(HDC hdc) {for (int i = 0; i < 10; i++){TextOut(hdc, 100, 20+i*25, TEXT("我是子線程1"), 6);}return 0; }DWORD WINAPI ThreadProc2(HDC hdc) {TextOut(hdc, 300, 20, TEXT("我是子線程2"), 6);return 0; }按照多線程原理,三個(主,2個子)線程的輸出是同步的;
程序要點如下;
在單個的C文件里面;2個線程函數必須預先聲明;
DWORD WINAPI ThreadProc1(HDC);
DWORD WINAPI ThreadProc2(HDC);
?
線程句柄;創建成功之后返回;
HANDLE hThread1, hThread2;
?
TextOut輸出,中文使用TEXT()宏;字符長度漢字也按一個;
TextOut(hdc, 500, 20, TEXT("我是主線程"), 5);
?
WaitForSingleObject(hThread1, INFINITE);
同步;C#里面應該封裝為CMutex之類的類了,記不清了;INFINITE,無限;
?
注意給線程2傳遞hdc,要再獲取一次hdc,否則線程2不會得到hdc能輸出;出了本線程要再獲取一次;
見此;
https://blog.csdn.net/bcbobo21cn/article/details/103739479
?
20+i*25;
每次輸出增加Y坐標25;默認字體大約高為20像素,具體記不清了;
總結
以上是生活随笔為你收集整理的Win32 API 多线程编程示例 - 窗口版的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 一些VC++ 系统类通用类
- 下一篇: 控制台和Win32 API程序输出变量地