mfc listctr 选中一行后 如何在失去焦点后仍然保持选中状态?
时间: 2024-10-15 20:13:44 浏览: 48
在 MFC 的 `ListCtrl` 中,如果你想让用户选中的一行在失去焦点后依然保持选中状态,你需要做的是在适当的地方记录下选中的索引,并且每次在窗口失去焦点时检查这个索引。可以考虑使用 `OnLostFocus` 或者 `OnDeactivate` 等窗口事件来进行这样的操作。以下是简单的一种实现方法:
首先,你需要在一个成员变量中存储选中的行索引,例如:
```cpp
CMyListCtrl::CMyListCtrl()
{
m_lastSelectedIndex = -1; // 初始化为未选中
}
```
然后,在 `OnSetFocus` 或 `OnGotFocus` 事件中,如果获得了焦点并且之前有选中项,设置选中状态:
```cpp
void CMyListCtrl::OnSetFocus(CWnd* pOldWnd)
{
if (m_lastSelectedIndex != -1)
{
SetSel(m_lastSelectedIndex, TRUE); // 设置选中状态
}
// ...其他 OnSetFocus 处理
}
// 类似地,在 OnGotFocus 事件中也可以处理这种情况
void CMyListCtrl::OnGotFocus(CWnd* /*pNewWnd*/)
{
// ...此处与 OnSetFocus 类似
}
```
接下来,在 `OnLostFocus` 或 `OnDeactivate` 事件中,检查是否有选中的行,如果有,则保留选中状态:
```cpp
void CMyListCtrl::OnLostFocus(CWnd* /*pNewWnd*/)
{
if (m_lastSelectedIndex != -1)
{
SetSel(m_lastSelectedIndex, TRUE);
}
// ...其他 OnLostFocus 处理
}
void CMyListCtrl::OnDeactivateApp(BOOL b自来由)
{
// 当应用程序失去焦点时同样处理
if (m_lastSelectedIndex != -1)
{
SetSel(m_lastSelectedIndex, TRUE);
}
// ...其他 OnDeactivateApp 处理
}
```
这样,无论何时用户从 `ListCtrl` 外部返回,只要他们之前选过一项,那项都会继续保持选中状态。
阅读全文
相关推荐















