This article introduces an operation that is often encountered in MFC programming: how to add a thread? Without further ado, let's go directly to the steps.
First create a new thread_op.h and thread_op.c files.
I added an image processing thread here, the header file is as follows:
#pragma once
#include <stdlib.h>
#include "afxwin.h"
#define WM_CONF_IMGPROC WM_USER+101 // 该宏至关重要
enum TEST_RES_CODE {
TR_FAIL,
TR_SUCCESS,
TR_EXCEPTION,
};
typedef struct TestResult {
bool isbrpass;
bool isdarkpass;
long brnum;
}TestResult;
typedef struct ImgThreadPra {
CWnd* pDlg;
int size;
}ImgThreadPra;
UINT imgProcThread(LPVOID pParam);
The corresponding implementation files are as follows:
#include <stdlib.h>
#include "afxwin.h"
#include "thread_op.h"
UINT imgProcThread(LPVOID pParam)
{
ImgThreadPra* pStruct = (ImgThreadPra*)pParam;
if (pStruct == NULL || pStruct->pDlg == NULL)
return -1;
/* 将结果传递给主线程 */
pStruct->pDlg->SendMessage(WM_CONF_IMGPROC, 0, (long)* testResult);
}
Next, add the object to the class in the dialog header file.
CWinThread *pTestThread;
TestThreadPra imgTestThreadPra;
LRESULT WindowProc(UINT message, WPARAM WParam, LPARAM lParam);
The connection with the main dialog box is established in the initialization interface of the main program of the dialog box:
ImgThreadPra.pDlg = this;
After that, some operations that you want to perform after clicking the button are thrown to other threads for operation , such as:
void CguiDlg::OnBnClickedOk()
{
// TODO: 在此添加控件通知处理程序代码
CDialogEx::OnOK();
pTestThread = AfxBeginThread(imgProcThread, &imgTestThreadPra);
}
Finally, add case processing to the switch in windowProc :
LRESULT testTool::WindowProc(UINT message, WPARAM WParam, LPARAM lParam)
{
TestResult *ret = NULL;
switch WM_CONF_IMGPROC:
testResult = (TestResult*)lParam;
break;
return CDialog::WindowProc(message, wParam, lParam);
}