简体   繁体   English

如何在C#Winforms中禁用复制粘贴选项

[英]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 .. 我有两个Winform应用程序,当我尝试从该ProcessCmdKey复制粘贴文本正确地工作如果我做了检查它没有粘贴..

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 .. 如果我专注于其他Windows表单文本没有被粘贴...有什么办法..

   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 iI try to achieve same the same for Notepad wordpad. 当我尝试为记事本wordpad实现相同的功能时。 It getting pasted. 它被粘贴了。

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 您需要更多工作来获得可行的解决方案,因为您需要自己拦截Ctrl + C并将数据放入剪贴板,而不是使用(根据定义)可用于每个应用程序的预定义数据格式

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) 如果您遵循此方法,其他应用程序将无法使用您的自定义格式(当然,如果安全性是真正的问题,则需要进行更多调整)

当应用程序最小化或失去焦点时,您可以清除剪贴板文本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM