文本框:禁用“粘贴"选项,同时允许右键单击“剪切"和“复制" [英] TextBox : Disable the 'Paste' option whilst allowing 'Cut' and 'Copy' on Right-click

查看:61
本文介绍了文本框:禁用“粘贴"选项,同时允许右键单击“剪切"和“复制"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 C# WinForms 中有一个 TextBox 组件.

I have a TextBox component in C# WinForms.

当我右键单击它时,我想禁用粘贴选项,同时仍允许用户进行剪切和复制.

When I Right-click on it, I would like to disable the paste option, whilst still allowing users to Cut and Copy.

我研究了几个选项,都不能完全满足我的要求 -

I have investigated a few options, neither of which fully meet my requirements -

  1. 如果我使用这个选项,它会阻止我不想要的剪切和复制以及粘贴.

  1. If I use this option, it will prevent Cut and Copy along with Paste which I do not want.

txt.ShortcutsEnabled = false;

如果我覆盖了 TextBoxContextMenu,我将不得不在新的上下文菜单中自己编写剪切和复制功能.

If I override the ContextMenu of TextBox, I will have to write the Cut and Copy Features myself in the new context menu.

txt.ContextMenu = new ContextMenu();//或其他一些

是否有任何选项可以仅禁用默认上下文菜单的粘贴选项,保留剪切和复制?

Are there any options I can use to disable only the Paste option of the default context menu, retaining Cut and Copy?

推荐答案

假设 Paste 菜单项始终是文本框上下文菜单中的第五个元素(从零开始,分隔符也算作项),您可以将 TextBox 类(此处:CustomMenuTextBox)并覆盖 WndProc 方法以禁用该特定菜单项:

Assuming the Paste menu item is always the fifth element in the textbox context menu (zero-based and a separator counts as item too), you could subclass the TextBox class (here: CustomMenuTextBox) and override the WndProc method to disable that specific menu item:

public static class User32
{
    [DllImport("user32.dll")]
    public static extern bool EnableMenuItem(IntPtr hMenu, uint uIDEnableItem, uint uEnable);
}

public class CustomMenuTextBox : TextBox
{
    protected override void WndProc(ref Message m)
    {
        if (m.Msg == 0x0093 /*WM_UAHINITMENU*/ || m.Msg == 0x0117 /*WM_INITMENUPOPUP*/ || m.Msg == 0x0116 /*WM_INITMENU*/)
        {
            IntPtr menuHandle = m.Msg == 0x0093 ? Marshal.ReadIntPtr(m.LParam) : m.WParam;

            // MF_BYPOSITION and MF_GRAYED
            User32.EnableMenuItem(menuHandle, 4, 0x00000400 | 0x00000001);
        }

        base.WndProc(ref m);
    }
}

基于 将项目添加到默认的 TextBox 上下文菜单.

这篇关于文本框:禁用“粘贴"选项,同时允许右键单击“剪切"和“复制"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆