专注收集记录技术开发学习笔记、技术难点、解决方案
网站信息搜索 >> 请输入关键词:
您当前的位置: 首页 > C#

winform如何判断右键事件从哪个控件上发生的

发布时间:2011-06-21 11:31:27 文章来源:www.iduyao.cn 采编人员:星星草
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控件中
友情提示:
信息收集于互联网,如果您发现错误或造成侵权,请及时通知本站更正或删除,具体联系方式见页面底部联系我们,谢谢。

其他相似内容:

热门推荐: