简体   繁体   English

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

[英]How to create a right click event handler in c#

I would please like to know how to display a context menu when you right click on the window. 我想知道当您右键单击窗口时如何显示上下文菜单。

Here is my code so far : 到目前为止,这是我的代码:

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");
}

AFAIK there is no direct RightClick event in winforms. AFAIK在winforms中没有直接的RightClick事件。 You can use the mousedown event to achieve this 您可以使用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");
            }
        }

in form cs file you can attach your context menu like this.. 在表格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");
    }

You should use MouseDown . 您应该使用MouseDown Then you can get the clicked button with e.Button and the coordinates with eX and eY . 然后,您可以使用e.Button获得单击的按钮,并通过eXeY获得坐标。

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

Add a ContextMenuStrip control to the form (note, it does not display on the form but is instead shown at the bottom of the designer). 向窗体添加一个ContextMenuStrip控件(注意,它不会显示在窗体上,而是显示在设计器的底部)。

In the form's ContextMenuStrip property, choose the name of the ContextMenuStrip control you just added to the form. 在窗体的ContextMenuStrip属性中,选择刚添加到窗体的ContextMenuStrip控件的名称。

That's it. 而已。 HansPassant stated this in a comment to the question but I think it is being overlooked. 汉斯·帕桑特(HansPassant)在对问题的评论中指出了这一点,但我认为它被忽略了。

The ContextMenuStrip property is a property of many UI controls that you would use the same technique for. ContextMenuStrip属性是您将使用相同技术的许多UI控件的属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM