kna*_*ser 6 c++ mfc multithreading thread-safety
我在MFC中有一个带有CStatusBar的对话框.在一个单独的线程中,我想更改状态栏的窗格文本.但MFC抱怨断言?怎么做?一个示例代码会很棒.
您可以将私人消息发布到主框架窗口,然后“询问”以更新状态栏。该线程将需要主窗口句柄(不要使用CWnd对象,因为它不会是线程安全的)。这是一些示例代码:
static UINT CMainFrame::UpdateStatusBarProc(LPVOID pParam);
void CMainFrame::OnCreateTestThread()
{
// Create the thread and pass the window handle
AfxBeginThread(UpdateStatusBarProc, m_hWnd);
}
LRESULT CMainFrame::OnUser(WPARAM wParam, LPARAM)
{
// Load string and update status bar
CString str;
VERIFY(str.LoadString(wParam));
m_wndStatusBar.SetPaneText(0, str);
return 0;
}
// Thread proc
UINT CMainFrame::UpdateStatusBarProc(LPVOID pParam)
{
const HWND hMainFrame = reinterpret_cast<HWND>(pParam);
ASSERT(hMainFrame != NULL);
::PostMessage(hMainFrame, WM_USER, IDS_STATUS_STRING);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
代码来自内存,因为我在家中无法访问编译器,因此对于任何错误,我们深表歉意。
WM_USER
您可以注册自己的Windows消息来代替使用:
UINT WM_MY_MESSAGE = ::RegisterWindowsMessage(_T("WM_MY_MESSAGE"));
Run Code Online (Sandbox Code Playgroud)
CMainFrame
例如,将以上内容设为静态成员。
如果使用字符串资源太基础,那么让线程在堆上分配字符串,并确保CMainFrame更新函数将其删除,例如:
// Thread proc
UINT CMainFrame::UpdateStatusBarProc(LPVOID pParam)
{
const HWND hMainFrame = reinterpret_cast<HWND>(pParam);
ASSERT(hMainFrame != NULL);
CString* pString = new CString;
*pString = _T("Hello, world!");
::PostMessage(hMainFrame, WM_USER, 0, reinterpret_cast<LPARAM>(pString));
return 0;
}
LRESULT CMainFrame::OnUser(WPARAM, LPARAM lParam)
{
CString* pString = reinterpret_cast<CString*>(lParam);
ASSERT(pString != NULL);
m_wndStatusBar.SetPaneText(0, *pString);
delete pString;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
不完美,但这是一个开始。
归档时间: |
|
查看次数: |
10124 次 |
最近记录: |