Wednesday, February 3, 2010

How to disable Copy / Paste in windows desktop Application using c#

class PreventClipboardOperationsTextBox : TextBox
{
// Default dummy context menu
private System.Windows.Forms.ContextMenu _contextMenu;

// Constants
private const Keys CopyKeys = Keys.Control | Keys.C;
private const Keys CutKeys = Keys.Control | Keys.X;
private const Keys PasteKeys = Keys.Control | Keys.V;

public PreventClipboardOperationsTextBox()
{
// Create a dummy context menu to prevent the
// default Copy/Cut/Paste context menu from showing up
_contextMenu = new ContextMenu();
this.ContextMenu = _contextMenu;
}

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
// If any of the Copy/Cut/Paste shortcut keys are pressed,
// then just return true to indicate that the command key has already been processed
if((keyData == CopyKeys) || (keyData == CutKeys) || (keyData == PasteKeys))
{
return true;
}
else
{
return base.ProcessCmdKey(ref msg, keyData);
}
}
};