[英]How to change pane text of status bar from a thread in MFC?
我在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;
}
代碼來自內存,因為我在家里無法訪問編譯器,所以現在為任何錯誤道歉。
您可以注冊自己的Windows消息,而不是使用WM_USER
:
UINT WM_MY_MESSAGE = ::RegisterWindowsMessage(_T("WM_MY_MESSAGE"));
例如,將上面的內容設置為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;
}
不完美,但這是一個開始。
也許這可以幫到你: 如何從MFC中的線程訪問UI元素。
我自己不編寫C ++ / MFC代碼,但我在C#中遇到了類似的問題,這就是所謂的跨線程GUI更新。
您應該使用消息(使用Send-或PostMessage)來通知UI線程應更新狀態欄文本。 不要嘗試從工作線程更新UI元素,它一定會給你帶來痛苦。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.