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

解决方案 »

  1.   

    调试一把 看看sender是什么类型的
      

  2.   

    sender 就该是你点击的对象
      

  3.   

    lz,确定sender是null吗?我这里用了各种控件绑定contextMenuStrip都是非空对象:
    { [System.Windows.Forms.ContextMenuStrip], Name: contextMenuStrip1, Items: 2}具体绑定到的是什么控件呢?
      

  4.   

    如果绑定了contextMenuStrip1,捕捉不到e.buttons的右键事件
      

  5.   

    是空的 SourceControl也是空的 我绑定的是Label   Label是我动态生成的
      

  6.   

    控件绑定contextMenuStrip1后他就不为空了饿,不绑定他怎么展开的?
    你贴点代码
      

  7.   

     Label l = new Label();
                            l.Name = i.ToString();
                            l.Size = new Size(50, 20);
                            l.Text = t.Rows[i]["b_name"].ToString();
                            l.Location = new Point(100 + i * 110, 100 + i * 20);
                            l.Parent = pictureBox1;
                            l.BackColor = Color.Transparent;
                            l.MouseMove += new MouseEventHandler(p_MouseMove);
                            l.MouseDown += new MouseEventHandler(p_MouseDown);
            void p_MouseDown(object sender, MouseEventArgs e)
            {
                if (e.Button == MouseButtons.Left)
                {
                    downPoint = e.Location;
                }
                if (e.Button == MouseButtons.Right)
                {
                    contextMenuStrip1.Show(Control.MousePosition);
                }
            }
      

  8.   

    你这个不叫绑定 contextMenuStrip1
      

  9.   

            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);
            }
    你的代码改的
      

  10.   

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