屏蔽ComboBox右键菜单(上下文菜单)

.net框架2.0,WinForm中,有些可编辑控件有默认的系统上下文菜单(右键弹出的),有时候需要屏蔽掉这些默认的菜单,不显示任何菜单或显示自定义的菜单。

在屏蔽的时候,有些可以通过继承控件,然后重写WndProc函数来截获Windows消息0x7B来屏蔽右键,比如对于TextBox是可行的。

对ComboBox却不可行,因为ComboBox实际是由多个小控件组合成的(包含TextBox),所有无法通过截获0X7B消息来屏蔽其上下文菜单。

对于ComboBox控件,网上搜索之后发现两种可行方案,都要调用Windows API,所有首先需添加应用

 

using System.Runtime.InteropServices;

 

方案一:

不需要继承ComboBox,直接在主窗体类中,添加如下代码
        [DllImport("user32.dll")]
        public static extern IntPtr GetWindow(IntPtr hWnd, uint uCmd);
        public const uint GW_CHILD = 5;

        public class SubWindow : NativeWindow
        {
            protected override void WndProc(ref Message m)
            {
                const int WM_CONTEXTMENU = 0x007B;
                switch (m.Msg)
                {
                    case WM_CONTEXTMENU: return;
                }
                base.WndProc(ref m);
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            SubWindow vSubWindow = new SubWindow();

            vSubWindow.AssignHandle(GetWindow(comboBox1.Handle, GW_CHILD));
        }

 

 

 

 

 方案二:

首先需要继承ComboBox,然后在子类实现里添加如下代码 

public partial class ComboEx : ComboBox
{
        [DllImport("user32.dll ")]
        static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
        public ComboEx()
        {
            InitializeComponent();
            IntPtr ehWnd = FindWindowEx(base.Handle, IntPtr.Zero, "Edit", "");
            SubClassHwnd sub = new SubClassHwnd();
            sub.AssignHandle(ehWnd);
        }

        protected override void WndProc(ref   Message m)
        {
            if (m.Msg == 0x7b)
                return;
            base.WndProc(ref   m);
        }

        public class SubClassHwnd : System.Windows.Forms.NativeWindow
        {
            protected override void WndProc(ref   Message m)
            {
                if (m.Msg == 0x7b)
                    return;
                base.WndProc(ref   m);
            }
        }

}

 

 

posted @ 2010-03-26 13:47  hapus  阅读(1348)  评论(0编辑  收藏  举报