如何在c#中创建右键单击事件处理程序

时间:2014-03-02 10:38:29

标签: c# winforms

我想知道如何在右键单击窗口时显示上下文菜单。

到目前为止,这是我的代码:

private void ShowContextMenu_RightClick(object sender, EventArgs e)
{
    toolStripMenuItem5.Visible = true;
}
private void toolStripMenuItem5_Click(object sender, EventArgs e)
{
    MessageBox.Show("Hi there this is my 3rd app which is *animation*.", "Programmed by D & K");
}

4 个答案:

答案 0 :(得分:4)

AFAIK winforms中没有直接的RightClick事件。您可以使用mousedown事件来实现此目的

  private void toolStripButton1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                MessageBox.Show("Hi there this is my 3rd app which is *animation*.", "Programed by D & K");
            }
        }

答案 1 :(得分:2)

在表单cs文件中,您可以附加这样的上下文菜单..

    public Form1()
    {
        InitializeComponent();

        //Create right click menu..
        ContextMenuStrip s = new ContextMenuStrip();

        // add one right click menu item named as hello           
        ToolStripMenuItem hello = new ToolStripMenuItem();
        hello.Text = "Hello";

        // add the clickevent of hello item
        hello.Click += hello_Click;

        // add the item in right click menu
        s.Items.Add(hello);

        // attach the right click menu with form
        this.ContextMenuStrip = s;
    }

    void hello_Click(object sender, EventArgs e)
    {
        MessageBox.Show("Hello Clicked");
    }

答案 2 :(得分:1)

您应该使用MouseDown。然后,您可以使用e.Buttone.Xe.Y的坐标获得点击的按钮。

private void Form1_MouseDown(object sender, MouseEventArgs e)
{
    MessageBox.Show(e.Button.ToString() + " " + e.X + " " + e.Y);
}

答案 3 :(得分:0)

将ContextMenuStrip控件添加到表单中(注意,它不会显示在表单上,​​而是显示在设计器的底部)。

在表单的ContextMenuStrip属性中,选择名称您刚刚添加到表单中的ContextMenuStrip控件。

就是这样。 HansPassant在对这个问题的评论中说明了这一点,但我认为它被忽略了。

ContextMenuStrip属性是许多UI控件的属性,您可以使用相同的技术。