Girish Mulye
Girish Mulye

Reputation: 1

Implementing barcode scanner in my (WPF MVVM ) application

I am stuck at a point in my WPF MVVM Application. My application must get the barcode data scanned by user (USB Barcode scanner) and compare the scanned data with my DB. I have a text box on screen and want to keep continuous focus on that textbox. user may go anywhere in the application but after coming back on main screen the focus must actually get on same text box.

I have implemented

FocusManager.FocusedElement="{Binding ElementName=TextBox2}" 

to my code file but it work only when screen loads. after doing some another action the focus gets loss. I want to get it back the focus back after closing another window or when he come back to main screen.

I have tried by giving TextBox2.Focus(); after all action is done but wont work for me.

Upvotes: 0

Views: 332

Answers (1)

Sir Rufo
Sir Rufo

Reputation: 19106

You can use the PreviewKeyDown from the window and set the focus to the TextBox

private void Window_PreviewKeyDown( object sender, KeyEventArgs e )
{
    if ( !BarcodeTextBox.IsFocused && BarcodeTextBox.Focusable )
    {
        BarcodeTextBox.SelectAll();
        BarcodeTextBox.Focus();
    }
}

You may want to filter out some keys as f.i. ENTER etc.

Upvotes: 1

Related Questions