简体   繁体   English

在C#中运行时添加菜单项

[英]Adding menu items during runtime in C#

I'm still working on getting a menu to display all of the input devices on a computer- pardon my third question in something that is probably very simple. 我仍在努力获取一个菜单来显示计算机上的所有输入设备 - 请原谅我的第三个问题可能非常简单。

Here's the code: 这是代码:

List<MenuItem> inputDevice = new List<MenuItem>();
MenuItem myMenuItemInputDevices = new MenuItem("&Input Devices");
sgFileMenu.MenuItems.Add(myMenuItemInputDevice);
for (int i = 0; i < DeviceCount; i++)
{
    inputDeviceMenu.Add(new MenuItem(inputName[i]));
    myMenuItemInputDevices.MenuItems.Add(inputDeviceMenu[i]);
    myMenuItemInputDevices.Click += new System.EventHandler(this.myMenuItemInputDeviceClick);
}

This seems to work just fine, the menu items are added, everything is good, but clicks on the dropdown list are not working. 这似乎工作得很好,菜单项添加,一切都很好,但点击下拉列表不起作用。 I've done other work with menus, and clicks in other code are working correctly. 我已经完成了菜单的其他工作,其他代码中的点击工作正常。 I tried putting 我尝试过

myMenuItemInputDevices.Click += new System.EventHandler(this.myMenuItemInputDeviceClick);

outside of the {}, just in case that was the right way to do it, but that didn't help. 在{}之外,以防这是正确的方法,但这没有帮助。

What am I missing? 我错过了什么?

You want this 你要这个

List<MenuItem> inputDevice = new List<MenuItem>();
MenuItem myMenuItemInputDevices = new MenuItem("&Input Devices");
sgFileMenu.MenuItems.Add(myMenuItemInputDevice);
for (int i = 0; i < DeviceCount; i++)
{
    inputDeviceMenu.Add(new MenuItem(inputName[i]));
    inputDeviceMenu[i].Click += new System.EventHandler(this.myMenuItemInputDeviceClick);
    myMenuItemInputDevices.MenuItems.Add(inputDeviceMenu[i]);
    myMenuItemInputDevices.Click += new System.EventHandler(this.myMenuItemInputDeviceClick);
}

EDIT: It is pretty obvious that the Menu Items that you are trying to add does not have any Click event method hooked up. 编辑:很明显,您尝试添加的菜单项没有连接任何Click事件方法。

    inputDeviceMenu.Add(new MenuItem(inputName[i]));

You are just adding them. 你只是添加它们。

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

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