I have a legacy MFC application with GUI, where some of the components are of type Edit Control
, which is simply a plain text box.
When a user highlights some text in those components and pushes Ctrl+C on the keyboard, nothing is copied to the clipboard. I can only copy using mouse right click and Copy from the context menu.
// MyWindow.h
class CMyWindow : CDialogEx {
public:
afx_msg void OnEditCopy();
afx_msg void OnUpdateEditCopy(CCmdUI *pCmdUI);
}
// MyWindow.cpp
BEGIN_MESSAGE_MAP(CMyWindow, CDialogEx)
ON_COMMAND(ID_EDIT_COPY, &CMyWindow::OnEditCopy)
ON_UPDATE_COMMAND_UI(ID_EDIT_COPY, &CMyWindow::OnUpdateEditCopy)
END_MESSAGE_MAP()
// MyWindow.cpp
void CMyWindow::OnEditCopy()
CWnd *wnd = GetFocus();
CEdit *myTextEdit = (CEdit*)GetDlgItem(IDC_EDIT_TEXT);
if (wnd == myTextEdit) {
myTextEdit->Copy();
}
MessageBox("check1");
}
void CMyWindow::OnUpdateEditCopy(CCmdUI *pCmdUI)
{
CWnd *wnd = GetFocus();
CEdit *myTextEdit = (CEdit*)GetDlgItem(IDC_EDIT_TEXT);
int start, end;
if (wnd == myTextEdit)
{
myTextEdit->GetSel(start, end);
pCmdUI->Enable(end > start);
}
MessageBox("check2");
}
Yet, when highlighting text and hitting Ctrl+C, trying to copy text from the Edit Control
widgets to the clipboard, the above defined methods are not called. No message box pops, and I can also see with the debugger that it does not enter any breakpoint within any of the two methods. They are also not called when choosing "Copy" from the context menu.
Any idea how to proceed?
Turned out that the problem was that someone had already overridden the Ctrl+C
event, regardless of the widget being in focus:
if (pressedCtrl && pMsg->wParam == VK_C_KEY) {
CopyToClipboardOverride();
return TRUE;
}
So, this solved my problem: if my Edit Control is in focus and has some non-empty selection, then it will skip the override and let the event propagate to its natural customers. I don't even need to call .Copy()
explicitly, as it happens naturally:
if (pressedCtrl && pMsg->wParam == VK_C_KEY) {
CWnd *wnd = GetFocus();
CEdit *myTextEdit = (CEdit*)GetDlgItem(IDC_EDIT_TEXT);
if (wnd == myTextEdit) {
int start, end;
myTextEdit->GetSel(start, end);
if (start != end) {
// A non-empty selection case
// This allows the event to keep going to the "next client"
return FALSE;
}
}
CopyToClipboardOverride();
return TRUE;
}