Click here to Skip to main content
15,890,123 members
Articles / Desktop Programming / MFC
Tip/Trick

Subclassing CEdit to disable clipboard operations

Rate me:
Please Sign up or sign in to vote.
4.50/5 (4 votes)
27 May 2010CPOL 18K   3  
Clipboard operations like cut, copy, paste on a normal CEdit control can be disabled usng subclassing.

The MFC CEdit class provides no simple way to prevent user from copying the contents of the corresponding Edit Control or pasting text into it or getting a context menu. Using subclassing and handling the WM_COPY, WM_PASTE, WM_CONTEXTMENU these operations can be disabled in a very simple way.

The code sample is very short and self explanatory. Most of the code is AppWizard generated. CPDEdit.* are the 2 main files of interest.

CPDEdit.h

-----------
class CPDEdit: public CEdit
{ 
public:
DECLARE_MESSAGE_MAP()
afx_msg LRESULT OnCopy(WPARAM, LPARAM);
afx_msg LRESULT OnPaste(WPARAM, LPARAM);
afx_msg LRESULT OnContextMenu(WPARAM, LPARAM);
}; 
CPDEdit.cpp
-----------
BEGIN_MESSAGE_MAP(CPDEdit, CEdit)
ON_MESSAGE(WM_COPY, OnCopy)
ON_MESSAGE(WM_PASTE, OnPaste)
ON_MESSAGE(WM_CONTEXTMENU, OnContextMenu)
END_MESSAGE_MAP()
LRESULT CPDEdit::OnCopy(WPARAM, LPARAM) {
return 0;
}
LRESULT CPDEdit::OnPaste(WPARAM, LPARAM) {
return 0;
}
LRESULT CPDEdit::OnContextMenu(WPARAM, LPARAM) {
return 0;
}

CPDEdit is the class derived from CEdit used to subclass the edit control. It traps the WM_COPY, WM_PASTE and WM_CONTEXTMENU messages and simply ignores them. Within your Dialog class change the type of control from CEdit to CPDEdit:

// CEdit m_edit;
CPDEdit m_edit;

And in the InitDialog() function subclass the control:

m_edit.SubclassDlgItem(IDC_EDIT, this);

Note that if you are using DDX with a control type then you don't need to call SubclassDlgItem because DDX internally calls it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --