Search code examples
c#.netwinformscontrolsfocus

How to determine which control on form has focus?


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 and check the value of KeyDown.

I want to be able to use this functionality on several TextBox controls which each are associated with a different Button.

My question is how do I know which control caused the KeyPress event? The sender is listed as the form itself.

G


Solution

  • 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!