Share via


FocusManager.TryFocusAsync(DependencyObject, FocusState) Method

Definition

Asynchronously attempts to set focus on an element when the application is initialized.

public:
 static IAsyncOperation<FocusMovementResult ^> ^ TryFocusAsync(DependencyObject ^ element, FocusState value);
/// [Windows.Foundation.Metadata.RemoteAsync]
 static IAsyncOperation<FocusMovementResult> TryFocusAsync(DependencyObject const& element, FocusState const& value);
[Windows.Foundation.Metadata.RemoteAsync]
public static IAsyncOperation<FocusMovementResult> TryFocusAsync(DependencyObject element, FocusState value);
function tryFocusAsync(element, value)
Public Shared Function TryFocusAsync (element As DependencyObject, value As FocusState) As IAsyncOperation(Of FocusMovementResult)

Parameters

element
DependencyObject

The object on which to set focus.

value
FocusState

One of the values from the FocusState enumeration that specify how an element can obtain focus.

Returns

The FocusMovementResult that indicates whether focus was successfully set.

Attributes

Examples

Here, we show how to set focus on a WebView object, and, if that fails, restore focus to the original element.

async void MoveFocus(WebView webView)) 
{ 
    FocusMovementResult result; 
    result = await FocusManager.TryFocusAsync(webView, FocusState.Programmatic); 
    if (!result.Succeeded) 
    { 
        // Restore focus to original element. 
        this.Focus(FocusState.Programmatic); 
    } 
}

Remarks

Some objects, such as a WebView, can run in either the app process or in a separate process (see WebViewExecutionMode.SeparateProcess).

When an object runs in the app process, the following focus events occur as expected for both the previously focused object and the newly focused object:

However, if the newly focused object is running in a separate process some of these event behaviors can differ.

  • GetFocusedElement does not return the newly focused object until the TryFocusAsync operation completes.
  • The control losing focus receives its LosingFocus event synchronously, but does not receive LostFocus until the asynchronous operation completes.
  • The control getting focus receieves its GettingFocus event synchronously, but does not receive GotFocus until the asynchronous operation completes.

TryFocusAsync completes synchronously when called on an element running in the app process.

Applies to

See also