C# WinForm 多个单击事件处理程序用于类似功能 [英] C# WinForm multiple click event handlers for similar function
本文介绍了C# WinForm 多个单击事件处理程序用于类似功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一些 toolStripMenuItems 作为一系列网站的有用链接,代码的粗略示例如下:
I have a few toolStripMenuItems that act as a useful links for a series of websites, a rough example of the code would be something like:
private void toolStripMenuItem1_Click(object sender, EventArgs e)
{
Process.Start("http://www.google.com");
}
private void toolStripMenuItem2_Click(object sender, EventArgs e)
{
Process.Start("http://www.bing.com");
}
private void toolStripMenuItem3_Click(object sender, EventArgs e)
{
Process.Start("https://www.duckduckgo.com");
}
private void toolStripMenuItem4_Click(object sender, EventArgs e)
{
Process.Start("http://www.yahoo.com/");
}
...
有没有更优雅的方法来处理这个问题?
Is there a more elegant way to handle this?
推荐答案
要做的第一件事是对每个处理程序使用相同的处理程序:
The first thing to do is use the same handler for each one:
toolStripMenu1.Click += toolStripItemClick;
toolStripMenu2.Click += toolStripItemClick;
// etc
我会为此使用 Tag
属性,在构建 toolStripItems 时设置它:
I would use the Tag
property for this, set it when you're constructing the toolStripItems:
toolStripMenu1.Tag = "http://www.google.com";
然后定义您的处理程序:
And then define your handler:
private void toolStripItemClick(object sender, EventArgs e)
{
var c = (ToolStripMenuItem)sender;
Process.Start(c.Tag.ToString());
}
这篇关于C# WinForm 多个单击事件处理程序用于类似功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文