日期:2014-05-20  浏览次数:21088 次

winform怎么判断右键事件从哪个控件上发生的?
winform怎么判断右键事件从哪个控件上发生的?
我在contextMenuStrip1_Opening事件中用MessageBox.Show((sender as ContextMenuStrip).SourceControl.Name);这个方法提示说 未将对象引用设置到对象的实例

------解决方案--------------------
调试一把 看看sender是什么类型的
------解决方案--------------------
sender 就该是你点击的对象
------解决方案--------------------
lz,确定sender是null吗?我这里用了各种控件绑定contextMenuStrip都是非空对象:
{ [System.Windows.Forms.ContextMenuStrip], Name: contextMenuStrip1, Items: 2}

具体绑定到的是什么控件呢?
------解决方案--------------------
如果绑定了contextMenuStrip1,捕捉不到e.buttons的右键事件
------解决方案--------------------
控件绑定contextMenuStrip1后他就不为空了饿,不绑定他怎么展开的?
你贴点代码
------解决方案--------------------
C# code


        public Form1()
        {
            InitializeComponent();
            Label lbl = new Label();
            lbl.Text = "123";
            lbl.Name = "abc";
            this.Controls.Add(lbl);
            lbl.ContextMenuStrip = this.contextMenuStrip1;
            lbl.MouseDown += new MouseEventHandler(p_MouseDown);
        }
        private void p_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                this.contextMenuStrip1.Items.Clear();
                this.contextMenuStrip1.Items.Add(Control.MousePosition.ToString());
            }
        }
        private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
        {
            MessageBox.Show((sender as ContextMenuStrip).SourceControl.Name);
        }

------解决方案--------------------
你右击的contextMenuStrip1控件有没有和那个控件绑定,控件的属性里面有个ContextMenuStrip,把它和ContextMenuStrip1控件绑定再试试,比如datagridview控件有个ContextMenuStrip属性,把它绑定到你的ContextMenuStrip1控件中