@@ -45,6 +45,8 @@ public class NativeWebDialog : Core.IWebView, Core.IWebViewHolder, IDisposable
4545 private Color ? _initialDefaultBackground ;
4646 private bool _disposed ;
4747 private bool _dialogInitialized ;
48+ private bool _shown ;
49+ private bool _focusRequested ;
4850
4951 static NativeWebDialog ( )
5052 {
@@ -299,10 +301,19 @@ public Color? DefaultBackground
299301 }
300302 }
301303
304+ /// <summary>
305+ /// Gets or sets if the dialog moves keyboard focus to its web content when shown. Default is true.
306+ /// </summary>
307+ public bool ShowFocused { get ; set ; } = true ;
308+
302309 /// <inheritdoc cref="Core.INativeWebViewDialog.Closing"/>
303310 public event EventHandler ? Closing ;
304311 /// <inheritdoc cref="Core.INativeWebViewDialog.Show()"/>
305- public async void Show ( ) => ( await GetOrInitialize ( ) ) . Show ( ) ;
312+ public async void Show ( )
313+ {
314+ ( await GetOrInitialize ( ) ) . Show ( ) ;
315+ OnShown ( ) ;
316+ }
306317
307318#if WPF
308319 /// <summary>
@@ -345,6 +356,39 @@ public async void Show(TopLevel owner)
345356 {
346357 impl . Show ( ) ;
347358 }
359+
360+ OnShown ( ) ;
361+ }
362+
363+ /// <summary>
364+ /// Activates the dialog and moves keyboard focus to the web content hosted inside of it.
365+ /// </summary>
366+ public void Focus ( )
367+ {
368+ _focusRequested = true ;
369+ TryApplyFocus ( ) ;
370+ }
371+
372+ private void OnShown ( )
373+ {
374+ _shown = true ;
375+ _focusRequested |= ShowFocused ;
376+ TryApplyFocus ( ) ;
377+ }
378+
379+ private void TryApplyFocus ( )
380+ {
381+ // The adapter is typically created only after the dialog window was shown,
382+ // and native focus can't be moved before that.
383+ if ( ! _focusRequested || ! _shown
384+ || TryGetImpl ( ) is not { } impl
385+ || impl . TryGetAdapter ( ) is null )
386+ {
387+ return ;
388+ }
389+
390+ _focusRequested = false ;
391+ impl . Focus ( ) ;
348392 }
349393
350394#if WPF
@@ -501,6 +545,7 @@ private void DialogImplOnAdapterDestroyed(object? sender, Core.WebViewAdapterEve
501545 adapter . WebResourceRequested -= WebViewAdapterOnWebResourceRequested ;
502546 adapter . NewWindowRequested -= WebViewAdapterOnNewWindowRequested ;
503547 _dialogInitialized = false ;
548+ _shown = false ;
504549 AdapterDestroyed ? . Invoke ( this , e ) ;
505550 }
506551
@@ -532,6 +577,8 @@ private void DialogImplOnAdapterCreated(object? sender, Core.WebViewAdapterEvent
532577 else if ( _lastSource is ValueTuple < string , Uri ? > pair )
533578 adapter . NavigateToString ( pair . Item1 , pair . Item2 ) ;
534579 AdapterCreated ? . Invoke ( this , e ) ;
580+
581+ TryApplyFocus ( ) ;
535582 }
536583
537584 private void DialogImplOnClosing ( object ? sender , EventArgs e )
0 commit comments