我有一個舊專案,Windows Forms其中有 300 多個選單,整個 MDI 表單中都有選單單擊事件。有什么方法可以獲取字串中的點擊事件名稱(例如“toolStripMenuItem_Click”)?我這樣試過
foreach (ToolStripMenuItem menu in menuStrip.Items)
{
foreach (ToolStripDropDownItem submenu in menu.DropDownItems)
{
var _events= submenu.GetType()
.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance)
.OrderBy(pi => pi.Name).ToList();
}
}
但它總是回傳空的。實作這一目標的正確方法是什么?
uj5u.com熱心網友回復:
在運行時檢索事件處理程式并不容易,尤其是在 Forms 框架中,其中某些事件在后臺有特殊處理。
一種更簡單的方法(如果您在運行時不需要名稱但在設計時需要)是在您的MyForm.designer.cs檔案上使用正則運算式來提取點擊處理程式的名稱。
請參閱此示例來源:
private void button1_Click(object sender, EventArgs e)
{
string fileLocaton = @"C:\Users\nineb\source\repos\WindowsFormsApp37\WindowsFormsApp37\Form1.Designer.cs";
string fileContent = File.ReadAllText(fileLocaton);
// Find all menu items in the designer file
var matches = Regex.Matches(fileContent, @"System\.Windows\.Forms\.ToolStripMenuItem (. ?)\;");
foreach (Match match in matches)
{
string menuName = match.Groups[1].Value;
textBox1.AppendText("Menuitem " menuName Environment.NewLine);
// For each menu item, find all the event handlers
var clickMatches = Regex.Matches(fileContent,
@"this\." Regex.Escape(menuName) @"\.Click \ \= new System\.EventHandler\(this\.(. ?)\)\;");
foreach (Match clickMatch in clickMatches)
{
string handlerName = clickMatch.Groups[1].Value;
textBox1.AppendText("Eventhandler " handlerName Environment.NewLine);
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/537446.html
標籤:C#窗体
