If you are calling
CEdit::OnChar()
from your
CEditEx::OnChar()
, the default Undo should still work.
Because the default Undo of an edit control can only undo the last operation, implementation is simple: In
CEditEx::OnChar()
store the text in an undo member variable when the content is to be changed (e.g. when not handling a cursor key). In your
CEditEx::Undo()
restore the content by passing the text from the undo member variable to
SetWindowText()
.
To support undo for copy, cut, and paste operations, copy the text to the same variable in these handlers.
Updated answer for the updated question:
Add these to your class:
class CEditEx : public CEdit
{
...
public:
inline BOOL CanUndo() const { return m_bCanUndo; }
protected:
void SaveUndoText();
BOOL m_bCanUndo;
CString m_strWindowTextUndo;
...
public:
afx_msg void OnCut();
afx_msg void OnUndo();
}
And these to your implementation:
CEditEx::CEditEx()
{
m_bCanUndo = FALSE;
}
BEGIN_MESSAGE_MAP(CEditEx, CEdit)
...
ON_COMMAND(ID_EDIT_CUT, OnCut)
ON_COMMAND(ID_EDIT_UNDO, OnUndo)
END_MESSAGE_MAP
void CEditEx::SaveUndoText()
{
GetWindowText(m_strWindowTextUndo);
m_bCanUndo = TRUE;
}
void CEditEx::OnUndo()
{
if (m_bCanUndo)
{
CString strRedo;
GetWindowText(strRedo);
SetWindowText(m_strWindowTextUndo);
m_strWindowTextUndo = strRedo;
}
}
void CEditEx::OnCut()
{
int nStartChar, nEndChar;
GetSel(nStartChar, nEndChar);
if (nStartChar != nEndChar)
{
SaveUndoText();
CEdit::Cut();
}
}
void CEditEx::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags)
{
...
SaveUndoText();
...
}
Implement
OnClear()
and
OnPaste()
like
OnCut()
.