我有一个用作浮动控件的用户控件,我想将Tab键顺序仅限于我的用户控件,当它可见时。基本上我需要的是一个控件,其行为类似于无边框Form
。实际上它是Form
,但我需要在MainForm窗口中保留Focus,所以我不得不将它更改为UserControl
。
所以,设想一个Form
A(MainForm)和我的UserControl
B.B是A的子控件。假设Form A有一个按钮和一个TextBox,而且控件B也是有一个按钮和一个文本框。目前发生的安全性如下
当前发生的事情(自然标签顺序行为):
当只有A可见时(B不可见):
1. The user manually focuses A textbox
2. Press tab key
3. A button is focused
当A可见且B可见时:(自然标签顺序键如下):
1. The user manually focuses B textbox
2. Press tab key
3. B button is focused
4. Press tab key
5. A textbox is focused
6. Press tab key
7. A button is focused
我需要什么(我需要更改用户控件以保留焦点):
我真正需要的是 B控件保留其中的Tab键顺序,所以当B控件可见时我需要的是:
1. The user manually focuses B texbox
2. Press tab key
3. B button is focused
4. Press tab key
5. B textbox is focused
答案 0 :(得分:0)
您可以覆盖控件的KeyDown事件,并手动将焦点移动到应该获得焦点的控件上。
除此之外,我同意Will Hughes可能会打破导航......
答案 1 :(得分:0)
我假设您按下某个按钮可以切换B用户控件的可见性。如果它是可见的并具有焦点,那么它将保持焦点。只有当您将其切换为隐藏时,它才会失去焦点。如果是这种情况,您可以在A表单中尝试使用此代码,除非您隐藏用户控件,否则会将您的注意力集中在用户控件上:
// store when we last clicked the toggle B user control visibility
private Stopwatch _sinceLastMouseClick;
public Form1()
{
InitializeComponent();
// instantiate the stopwatch and start it ticking
_sinceLastMouseClick = new Stopwatch();
_sinceLastMouseClick.Start();
}
用于切换浮动B控件的单击处理程序上的可见性的按钮:
private void btnToggleBUserControlVisibility_Click(object sender, EventArgs e)
{
// reset the stopwatch because we just clicked it
_sinceLastMouseClick.Restart();
myUserControl1.Visible = !myUserControl1.Visible;
}
在您的父A表单中,处理浮动用户控件的Leave事件:
private void myUserControl1_Leave(object sender, EventArgs e)
{
// see if the mouse is over the toggle button
Point ptMouse = System.Windows.Forms.Control.MousePosition;
Point ptClient = this.PointToClient(ptMouse);
// if the mouse is NOT hovering over the toggle button and has NOT just clicked it,
// then keep the focus in the user control.
// We use the stopwatch to make sure that not only are we hovering over the button
// but that we also clicked it, too
if (btnToggleBUserControlVisibility != this.GetChildAtPoint(ptClient) ||
_sinceLastMouseClick.ElapsedMilliseconds > 100)
{
myUserControl1.Focus();
}
}
答案 2 :(得分:0)
最后我解决了问题,包括父控件中的以下代码:
private int WM_KEYDOWN = 0x100;
public override bool PreProcessMessage(ref Message msg)
{
Keys key = (Keys)msg.WParam.ToInt32();
if (msg.Msg == WM_KEYDOWN && key == Keys.Tab)
{
if (itemSearchControl.Visible)
{
bool moveForward = !IsShiftKeyPressed();
bool result = itemSearchControl.SelectNextControl(itemSearchControl.ActiveControl, true, true, true, true);
return true;
}
}
return base.PreProcessMessage(ref msg);
}
答案 3 :(得分:0)
从另一个问题,将其添加到您的UserControl xaml。
KeyboardNavigation.TabNavigation="Cycle"