我有一个CListCtrl,在其中我在一个单元格上方显示一个文本框,以允许用户编辑该单元格的文本。
这可行,但是基于用户窗口设置,我认为文本框不会针对不同的UI样式停留在正确的位置。
有谁知道一种可靠的方式将文本框窗口置于用户单击的单元格上方?这是我现在使用的代码。我不关心在其中添加值16的文本框的右侧。我只想要一种可靠的方法来获取将文本框的左侧和顶部放置在何处。
void FilesDialog::OnNMClickFiles(NMHDR *pNMHDR, LRESULT *pResult)
{
LPNMITEMACTIVATE temp = (LPNMITEMACTIVATE)pNMHDR;
//get the row number
nItem = temp->iItem;
//get the column number
nSubItem = temp->iSubItem;
if (nSubItem == 0 || nSubItem == -1 || nItem == -1)
{
*pResult = 0;
return;
}
//Retrieve the text of the selected subItem from the list
CString str = GetItemText(filesList.m_hWnd, nItem, nSubItem);
CRect rectList, rectDlg, rectCl;
CRect rectItem;
// Get the rectangle of the selected sub-item.
ListView_GetSubItemRect(filesList.m_hWnd, temp->iItem, temp->iSubItem, LVIR_BOUNDS, &rectItem);
//Get the Rectange of the listControl
::GetWindowRect(temp->hdr.hwndFrom, &rectList);
//Get the Rectange of the Dialog
::GetWindowRect(this->m_hWnd, &rectDlg);
GetClientRect(&rectCl);
//this->ScreenToClient(&rectCl);
int subY = rectDlg.Height() - rectCl.Height() - 5;
int lft = rectItem.left + rectList.left - rectDlg.left + 1;
int tp = rectItem.top + rectList.top - rectDlg.top - subY;
// When an item is cut off by the window on the right
// side, resize the text box so that the right side
// is at the edge of the list control.
int rtEdge = rectDlg.right - (rectDlg.right - rectCl.right);
int subWdth = 0;
if (lft + rectItem.Width() - 2 > rtEdge)
{
// 16 is just an arbitrary value that seems to work.
subWdth = 16 + (lft + rectItem.Width() - 2) - rtEdge;
}
// Move the edit box window over the cell.
editText.MoveWindow(lft, tp, rectItem.Width() - 2 - subWdth, rectItem.Height() - 1, true);
//Set the list Item text in the edit box.
::SetWindowText(editText.m_hWnd, str);
// Show the edit box and set focus to it.
::ShowWindow(editText.m_hWnd, SW_SHOW);
::SetFocus(editText.m_hWnd);
*pResult = 0;
}
谢谢。
最佳答案
这取决于editText
的创建方式。如果editText
的父级是ListView控件,例如:
editText.Create(WS_CHILD, CRect(0, 0, 1, 1), &filesList, 1);
这样就无需进行任何调整,只需按原样使用
rectItem
即可:void FilesDialog::OnNMClickFiles(NMHDR *pNMHDR, LRESULT *pResult)
{
LPNMITEMACTIVATE temp = (LPNMITEMACTIVATE)pNMHDR;
if (temp->iSubItem == 0 || temp->iSubItem == -1 || temp->iItem == -1)
{
*pResult = 0;
return;
}
CString str = filesList.GetItemText(temp->iItem, temp->iSubItem);
CRect rectItem;
filesList.GetSubItemRect(temp->iItem, temp->iSubItem, LVIR_BOUNDS, rectItem);
editText.SetWindowText(str);
editText.MoveWindow(rectItem, 1);
editText.ShowWindow(SW_SHOW);
*pResult = 0;
}
另一方面,如果
editText
的父级不是ListView控件,则editbox不会相对于ListView定位自身,因此必须调整其位置。例如,如果
editText
是在DoDataExchange
中初始化的,则按如下所示偏移rectItem
:POINT p = { 0 };
filesList.MapWindowPoints(this, &p, 1);
rectItem.OffsetRect(p.x, p.y);
...
editText.MoveWindow(rectItem, 1);
关于c++ - MFC CListCtrl在单元格上方显示文本框供用户编辑,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34941929/