0

可能重复:
面板没有获得焦点

我有一个有点烦人的情况。我有一个在 a 中保存的 WinForm PictureBoxPanel所以如果图片超过了我的表单具有的特定大小限制,我可以使图片可滚动)。

现在,为了使用户能够使用 MouseWheel 在面板中滚动,我必须输入以下代码:

Private Sub MyPanel_MouseEnter(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyPanel.MouseEnter
    MyPanel.Focus()
End Sub

这很好用,允许用户随意滚动图片。

现在,我的问题是我的表单上还有一个textbox我希望用户能够填写数据的表单。当用户单击文本框并将鼠标移到面板上时,挑战就出现了——这会使文本框失去控制并阻止用户键入。

我怎样才能最好地处理这种情况?

4

2 回答 2

0

Since I had to come up with some kind of a solution since this form is due for production, I coded up the following (which solved the problem), but if anyone has any better solutions, I'd love to hear them!!!

' Form-Level Variable stating whether the panel can take
' the focus away from the preceding control

Dim DontTakeAwayFocus As Boolean = False

Private Sub MyPanel_Click(sender As Object, e As EventArgs) Handles MyPanel.Click
  MyPanel.Focus()
End Sub

Private Sub MyPanel_MouseEnter(sender As Object, e As EventArgs) Handles MyPanel.MouseEnter
  If DontTakeAwayFocus Then Exit Sub
  MyPanel.Focus()
End Sub

Private Sub MyTxtBox_GotFocus(sender As Object, e As EventArgs) Handles MyTxtBox.GotFocus
  DontTakeAwayFocus = True
End Sub

Private Sub MyTxtBox_LostFocus(sender As Object, e As EventArgs) Handles MyTxtBox.LostFocus
  DontTakeAwayFocus = False
End Sub

What this allowed me to do was that if the textbox had focus, then you had to click on the panel to take the focus away, otherwise, the panel still kept the same functionality.

于 2012-11-13T21:08:52.257 回答
0

抢焦点?

考虑一下转移注意力是否真的是解决问题的正确方法。这很诱人,因为焦点/非焦点的区别是如此明显,而且看起来很容易。但它很快就会变成一团糟。

想象一下,您使用的第三方组件有时会在不应该的情况下窃取焦点。恼火的是,您会编写一些代码来重新获得焦点。问题解决了,不是吗?但现在有两个组件不恰当地窃取了焦点,而不是一个。而最终,用户将成为这场焦点战的受害者。

改为订阅TextBox事件

现在,您正在监听Panel. Panel让对事件做出反应的另一种方法MouseWheel是订阅表单上的适当事件Textbox,甚至订阅表单上所有控件的事件。

然后在您的处理程序中,检查鼠标是否在Panel. 如果是这样,请指示面板滚动。如有必要,不要忘记传播鼠标事件。

编辑

附加信息:

希望这可以帮助。

于 2012-11-13T21:16:31.470 回答