How to determine which control on form has focus?

后端 未结 4 607
轻奢々
轻奢々 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 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!

提交回复
热议问题