我有很多旧的Windows Forms应用程序,最终将被移植到WPF(这是一个大型应用程序,所以无法在一个迭代中完成),我已经通过在WPF中创建主菜单开始了此过程。Windows Forms应用程序是从该菜单打开的独立窗口。
Windows Forms应用程序正常打开和运行,但我遇到了一些问题,其中包括快捷键和Tab键的使用。Tab键无法移动焦点到下一个控件,而Alt键触发“&搜索”按钮的功能也不再起作用。
我做错了什么?
我通过将winform托管在WPF窗体内的WindowsFormsHost控件中,最终成功解决了这个问题。
public partial class MyWindow : Window
{
public MyWindow()
{
InitializeComponent();
Form winform = new Form();
// to embed a winform using windowsFormsHost, you need to explicitly
// tell the form it is not the top level control or you will get
// a runtime error.
winform.TopLevel = false;
// hide border because it will already have the WPF window border
winform.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.windowsFormsHost.Child = winform;
}
}
ShowDialog()
解决了选项卡问题,对我非常有帮助!我希望其他程序员也能在这里找到这个解决方案(对我来说很难找到)。 - zee我发现另一个处理Tab键焦点的方法是像这样覆盖OnKeyDown:
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.KeyCode == Keys.Tab)
{
HandleFocus(this, ActiveControl);
}
else
{
base.OnKeyDown(e);
}
}
internal static void HandleFocus(Control parent, Control current)
{
Keyboard keyboard = new Keyboard();
// Move to the first control that can receive focus, taking into account
// the possibility that the user pressed <Shift>+<Tab>, in which case we
// need to start at the end and work backwards.
System.Windows.Forms.Control ctl = parent.GetNextControl(current, !keyboard.ShiftKeyDown);
while (null != ctl)
{
if (ctl.Enabled && ctl.CanSelect)
{
ctl.Focus();
break;
}
else
{
ctl = parent.GetNextControl(ctl, !keyboard.ShiftKeyDown);
}
}
}
检查是否已分配IsTabStop =“True”
和TabIndex
。 对于Alt + Key
快捷方式,尝试使用下划线(_)字符代替&号(&)。