我终于找到了一个使用来自不同地方的代码的解决方案。我认为把它写在这里很重要,因为我在任何地方都没有找到完整的答案。即使是与这个问题相关的问题也很难找到。让我解释一下我做了什么:
1)重写Form中的ProcessMnemonic方法。
protected override bool ProcessMnemonic(char charCode)
{
// get the mnemonic key of the button that submits the form (accepts the form or performs some action)
char mnemonicChar = DesignerHelper.GetMnemonicChar(btnCreate);
// check if the button has a mnemonic key and if the mnemonic key pressed corresponds to it
if (mnemonicChar != ' ' && charCode == mnemonicChar)
{
// get the control that is focused. this could be the textbox where the mnemonic key was pressed
Control ctrl = DesignerHelper.FindFocusedControl(this);
if (ctrl != null)
{
// fire the necessary event to update the state of the controls. in my case it's leave event.
DesignerHelper.FireEvent(ctrl, "Leave", new EventArgs());
}
}
return base.ProcessMnemonic(charCode);
}
2)我自己的 DesignerHelper 类中可用的方法:
public static Control FindFocusedControl(Control control)
{
var container = control as ContainerControl;
while (container != null)
{
control = container.ActiveControl;
container = control as ContainerControl;
}
return control;
}
/// <summary>
/// Programatically fire an event handler of an object
/// </summary>
/// <param name="targetObject"></param>
/// <param name="eventName"></param>
/// <param name="e"></param>
public static void FireEvent(Object targetObject, string eventName, EventArgs e)
{
/*
* By convention event handlers are internally called by a protected
* method called OnEventName
* e.g.
* public event TextChanged
* is triggered by
* protected void OnTextChanged
*
* If the object didn't create an OnXxxx protected method,
* then you're screwed. But your alternative was over override
* the method and call it - so you'd be screwed the other way too.
*/
//Event thrower method name //e.g. OnTextChanged
String methodName = "On" + eventName;
MethodInfo mi = targetObject.GetType().GetMethod(
methodName,
BindingFlags.Instance | BindingFlags.NonPublic);
if (mi == null)
throw new ArgumentException("Cannot find event thrower named " + methodName);
mi.Invoke(targetObject, new object[] { e });
}
internal static char GetMnemonicChar(Button btn)
{
if (btn.UseMnemonic && btn.Text.Contains("&"))
{
return btn.Text.Substring(btn.Text.IndexOf("&") + 1, 1)[0];
}
return ' ';
}