How to determine which control on form has focus?

后端 未结 4 608
轻奢々
轻奢々 2021-01-11 10:20

I\'ve read elsewhere on here that to capture \"Enter\" key stroke in a text box and use it as if pushing a button I should set the KeyPreview property of the form to true an

相关标签:
4条回答
  • 2021-01-11 10:56

    Each form has a property for an "Accept" button & "Cancel" button, these are the buttons that get "clicked" when the user presses enter and escape respectively.

    You can change the default button as each control gets the focus (you can have one got focus event hander per button, and share it with a set of text boxes)

    If you do this then the apperance of the buttons change giving the user a visual cue telling them which button is the default.

    Alternatively, if you don't want to do that, you can use the "ActiveControl" property, and test to see which of the sets of text boxes it belongs to.

    Have you asked yourself, what should the default button be if it's not one of thse text boxes?

    0 讨论(0)
  • 2021-01-11 10:57

    You could use this code as a starting point to capture the key down events of the form. The ActiveControl is one that has the focus. In this example, it's flexible for adding other actions on "Enter" when you are in different TextBoxes on the form. It's VB.NET, but you should be able to easily convert to C#.

    Private Sub MyForm_KeyDown(ByVal sender As Object, _
        ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
    
        If e.KeyCode = Keys.Enter Then
            If Me.ActiveControl.Name = Me.TextBox1.Name Then
                ' This is the TextBox we want to be active to run filterByDeviceSN()
                filterByDeviceSN()
            ElseIf Me.ActiveControl.Name = Me.TextBox2.Name Then
                foo()
            End If
        End If
    End Sub
    
    0 讨论(0)
  • 2021-01-11 10:59

    Have you tried Form.ActiveControl?

    0 讨论(0)
  • 2021-01-11 11:05

    I've found a solution which appears to be working.

        private void DeviceForm_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13 && tstxtDeviceFilter.Focused)
            {
                filterByDeviceSN();
            }
        }
    

    I can't help but think there must be a better way though!

    --EDIT--EDIT--EDIT--EDIT--EDIT--

    Well, after looking at the suggestions below (thank you) I've found a 'better' way for me in this circumstance.

        this.tstxtDeviceFilter.KeyDown += new System.Windows.Forms.KeyEventHandler(this.tstxtDeviceFilter_KeyDown);
    
        private void tstxtDeviceFilter_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13)
            {
                filterByDeviceSN();
            }
        }
    

    Obviously by trapping the event on the textbox itself rather than the form I don't need to worry about focus. Once again I feel dumb for not thinking of that for so long!

    0 讨论(0)
提交回复
热议问题