Aravind
Aravind

Reputation: 177

How to Disable Copy Paste Options in C# Winforms

I have Two Winform Applications and when I try to Copy paste Text from that ProcessCmdKey Works Correctly if i made a check its not pasted ..

But when i try to paste my text in notepad its getting pasted ... I just want to Achieve COPY and PASTE of Text in same application

If I Focus on other Windows forms Text has not to be pasted... is there any way ..

   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)
    {

        bool bVal = false;
        Process[] p2 = Process.GetProcesses();
        foreach (Process pro in p2)
        {
            if (string.Compare(pro.ProcessName, "TestForm.vshost", true) == 0 && (keyData == CopyKeys) || (keyData == PasteKeys))
            {
                bVal = true;  // Text will be pasted 
                return true;
            }
            else
                return base.ProcessCmdKey(ref msg, keyData); // Text will not be pasted
        }
        return bVal;
    }

This works correctly. When i-I try to achieve same the same for Notepad wordpad. It getting pasted.

Upvotes: 0

Views: 1317

Answers (2)

Steve
Steve

Reputation: 216342

If you really want to be sure that other applications can't get the data in the clipboard you need to use a custom format and put your data in the clipboard yourself.

This is just an example how to do it. You need more work to have a working solution because you need to intercept the Ctrl+C yourself and put your data in the clipboard instead of using the predefined data formats that (by definition) are available for every application

public void cmdTest_Click(object sender, EventArgs e)
{
    Clipboard.SetData("MyCustomFormat", new MyData("This text should not be pasted"));
    if(Clipboard.ContainsData("MyCustomFormat"))
    {
        MyData result = Clipboard.GetData("MyCustomFormat") as MyData;
        MessageBox.Show(result.MyValue);
    }   
}

[Serializable]
class MyData
{
    string _internalValue;
    public MyData(string newValue)
    { _internalValue = newValue;}
    public string MyValue
    {
        get{return _internalValue;}
    }
}

If you follow this method other applications cannot use your custom format (of course, if security is a real concern more tweaking will be required)

Upvotes: 2

andy
andy

Reputation: 6079

You can clear the Clipboard text when your application is minimized or lost focus.

Upvotes: 0

Related Questions