This blocks you code
WaitForSingleObject(_hThread,INFINITE) ;
Small example:#define WIN32_LEAN_AND_MEAN
#include <windows.h>
INT_PTR CALLBACK MainDlgProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam);
void OnInitDialog(HWND hwndDlg);
void StartStopThr(HWND hwndDlg);
DLGTEMPLATE Dlg = {WS_POPUPWINDOW|WS_CAPTION|WS_VISIBLE|DS_3DLOOK|DS_CENTER,0,0,0,0,200,100};
DWORD DlgFill[2] = {0}; // for dialog, must be here after template in this example
HANDLE hThread1;
BOOL bRun;
int __cdecl WinMainCRTStartup(void)
{
ExitProcess(DialogBoxIndirectParam(GetModuleHandle(NULL), (LPDLGTEMPLATE)&Dlg, 0, MainDlgProc, 0));
}
INT_PTR CALLBACK MainDlgProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_COMMAND:
switch (LOWORD(wParam)) {
case 4001:
StartStopThr(hwndDlg);
return TRUE;
}
break;
case WM_INITDIALOG:
OnInitDialog(hwndDlg);
return TRUE;
case WM_CLOSE:
EndDialog(hwndDlg, 0);
return TRUE;
}
return FALSE;
}
void OnInitDialog(HWND hwndDlg)
{
CreateWindowEx(0,TEXT("BUTTON"),TEXT("Start"),
WS_CHILD|WS_VISIBLE,10,10,50,25,hwndDlg,(HMENU)4001,GetModuleHandle(NULL),0);
}
DWORD ThreadProc1(void* pPar)
{
int iCnt = 0;
while (bRun) {
TCHAR szTmp[100];
wsprintf(szTmp, TEXT("Thread1: %d"), iCnt++);
SetWindowText((HWND)pPar, szTmp);
Sleep(1000);
if (iCnt > 100) break;
}
SetDlgItemText((HWND)pPar, 4001, TEXT("Start"));
SetWindowText((HWND)pPar, TEXT("Thread1 Ends"));
bRun = 0;
return 0;
}
void StartStopThr(HWND hwndDlg)
{
if (bRun) {
bRun = 0; // ask to stop
//SetDlgItemText(hwndDlg, 4001, TEXT("Start"));
} else {
SetWindowText(hwndDlg, TEXT("Create Thread1"));
if ((hThread1 = CreateThread(NULL,0,ThreadProc1,hwndDlg,0,NULL)) != 0) {
SetDlgItemText(hwndDlg, 4001, TEXT("Stop"));
bRun = 1;
}
}
}