A quick way to disable copy-paste in a textbox in a WinForms application.

To disable the copy-paste in a textbox in winforms application, use the following code snippet

Two steps to be followed to disable the Copy-Paste feature in a textbox, 

i) Disable the default menu and associate the textbox with an empty context menu that has no menu items. (Mouse Actions)

ii) But, the user could use the Shortcut keys on the keyboard and perform these operations. So, Override the ProcessCmdKey method as shown below.  
   Declare two constants as shown below to avoid the Copy and Paste keys


// Constants private const Keys CopyKeys = Keys.Control | Keys.C; private const Keys PasteKeys = Keys.Control | Keys.V; protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { if((keyData == CopyKeys) || (keyData == PasteKeys)){ return true; } else{ return base.ProcessCmdKey(ref msg, keyData);} }
If the keys are not Copy or Paste keys , we should call the base class implementation.
Note: Return true, so that the Base Class functionality is suppressed.
By [)ia6l0 iii   Popularity  (4043 Views)