Collapse the table of content
Expand the table of content
Expand Minimize

UIElement.Focus Method

Updated: January 2010

Attempts to set focus to this element.

Namespace:  System.Windows
Assembly:  PresentationCore (in PresentationCore.dll)

public bool Focus()
You cannot use methods in XAML.

Return Value

Type: System.Boolean
true if keyboard focus and logical focus were set to this element; false if only logical focus was set to this element, or if the call to this method did not force the focus to change.



To be focusable, Focusable and IsEnabled must both be true.

Even if an element is focusable and enabled, event handling within a specific tree, (such as for a composite control) might respond to the preview focus events by not allowing focus there, thus this method would return false.

Focus in general is governed by two separate concepts: keyboard focus and logical focus, which are not always identical. For more information, see Focus Overview or Input Overview.

If calling Focus returns true, IsKeyboardFocused and IsKeyboardFocusWithin are also true.

If the related properties are not already true, when you call Focus, one or more of the following events are raised in the following order: PreviewLostKeyboardFocus, PreviewGotKeyboardFocus (source is the new focus target), IsKeyboardFocusedChanged, IsKeyboardFocusWithinChanged, LostKeyboardFocus, GotKeyboardFocus (source is the new focus target).

In order for this call to be successful, some other element in the application needed to have focus previously.

The following example sets focus to a TextBox referenced by Name, and then adjusts the position of the cursor within the TextBox.

void OnClickMoveToStart(object sender, RoutedEventArgs e)
    tbPositionCursor.Select(0, 0);

Windows 7, Windows Vista, Windows XP SP2, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

.NET Framework

Supported in: 3.5, 3.0




January 2010

Removed incorrect remarks.

Content bug fix.

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

© 2015 Microsoft