如何从MFC中的线程更改状态栏的窗格文本? [英] How to change pane text of status bar from a thread in MFC?

查看:692
本文介绍了如何从MFC中的线程更改状态栏的窗格文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在MFC中有一个对话框与CStatusBar。在单独的线程中,我想更改状态栏的窗格文本。然而,MFC抱怨声明?如何做?

I have a dialog in MFC with a CStatusBar. In a separate thread, I want to change the pane text of status bar. However MFC complains with asserts? How is it done? An example code would be great.

推荐答案

您可以在主框架窗口中发布私人消息,然后询问状态栏。线程将需要主窗口句柄(不要使用CWnd对象,因为它不会是线程安全的)。下面是一些示例代码:

You could post a private message to the main frame window and 'ask' it to update the status bar. The thread would need the main window handle (don't use the CWnd object as it won't be thread safe). Here is some sample code:

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;
}

代码来自内存,因为我没有访问编译器

The code is from memory as I don't have access to compiler here at home, so apologies now for any errors.

而不是使用 WM_USER ,您可以注册自己的Windows消息:

Instead of using WM_USER you could register your own Windows message:

UINT WM_MY_MESSAGE = ::RegisterWindowsMessage(_T("WM_MY_MESSAGE"));

使上面的 CMainFrame 例如

如果使用字符串资源太基本,那么让线程在堆上分配字符串,并确保CMainFrame更新函数删除它,例如:

If using string resources is too basic then have the thread allocate the string on the heap and make sure the CMainFrame update function deletes it, e.g.:

// 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;
}

不完美,但它是一个开始。

Not perfect, but it's a start.

这篇关于如何从MFC中的线程更改状态栏的窗格文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆