Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

UIElement.Focus Method

Attempts to focus the keyboard on this element.

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

public bool Focus ()
public final boolean Focus ()
public final function Focus () : boolean
You cannot use methods in XAML.

Return Value

true if keyboard focus could be set to this element; false if this method call did not force focus.

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.

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.

Focus in general is governed by two separate concepts: keyboard focus and logical focus, which are not always identical. This method sets the logical focus. There is no programmatic means to set keyboard focus specifically, this happens due to user input. For more information, see Input Overview.

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.Focus();
    tbPositionCursor.Select(0, 0);
}

Windows 98, Windows Server 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The Microsoft .NET Framework 3.0 is supported on Windows Vista, Microsoft Windows XP SP2, and Windows Server 2003 SP1.

.NET Framework

Supported in: 3.0

Community Additions

Show:
© 2014 Microsoft. All rights reserved.