簡體   English   中英

在WPF應用程序中按下Return鍵時如何模擬Tab鍵?

[英]How do I simulate a Tab key press when Return is pressed in a WPF application?

在WPF應用程序中,我有一個包含很多字段的窗口。 當用戶在填充每個字段后使用TAB鍵時,Windows會理解它會移動到下一個字段。 這是非常了解的行為。

現在我想要的是,它使模擬TAB鍵,實際上RETURN被擊中。 所以在我的WPF xaml中我添加了暗示KeyDown="userPressEnter"

在它背后的代碼中:

private void userPressEnter(object sender, KeyEventArgs e)
{
  if (e.Key == Key.Return)
  {
    e.Key = Key.Tab // THIS IS NOT WORKING
  }
}

現在,顯然這不起作用。 但我不知道的是,我如何使這項工作?


編輯1 ==>找到一個解決方案

我找到了幫助我的東西=)

private void userPressEnter(object sender, KeyEventArgs e)
{
 if (e.Key == Key.Return)
 {
   TraversalRequest request = new TraversalRequest(FocusNavigationDirection.Next);
   MoveFocus(request);
 }
}

這樣,焦點移動到下一個它可以找到:)

你可以在這里看一篇文章: http//social.msdn.microsoft.com/Forums/en/wpf/thread/c85892ca-08e3-40ca-ae9f-23396df6f3bd

這是一個例子:

private void textBox1_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                TraversalRequest request = new TraversalRequest(FocusNavigationDirection.Next);
                request.Wrapped = true;
                ((TextBox)sender).MoveFocus(request);
            }
        }
    protected override bool ProcessDialogKey(Keys keyData)
    {
        System.Diagnostics.Debug.WriteLine(keyData.ToString());

        switch (keyData)
        {
            case Keys.Enter:
                SendKeys.Send("{TAB}");
                break;
        }
        base.ProcessDialogKey(keyData);
        return false;
    }

我認為你應該使用它來模擬TAB:

SendKeys.Send("{TAB}");

代替

e.Key = Key.Tab

來源: http//msdn.microsoft.com/en-us/library/system.windows.forms.sendkeys.send.aspx

使用表單的SelectNextControl方法

SendKeys.Send或SendKeys.SendWait在WPF應用程序中不起作用,所以要回答原始問題

if (e.Key == Key.Return)
{    
    KeyEventArgs tabPressEventArgs = new KeyEventArgs(Keyboard.PrimaryDevice, Keyboard.PrimaryDevice.ActiveSource, 0, Key.Tab) { RoutedEvent = Keyboard.KeyDownEvent };
    InputManager.Current.ProcessInput(tabPressEventArgs); 
}

如何使SendKeys類像Winforms.SendKeys一樣工作

https://michlg.wordpress.com/2013/02/05/wpf-send-keys/

public static class SendKeys
{
    public static void Send(Key key)
    {
        if (Keyboard.PrimaryDevice != null) {
            if (Keyboard.PrimaryDevice.ActiveSource != null) {
                var e1 = new KeyEventArgs(Keyboard.PrimaryDevice, Keyboard.PrimaryDevice.ActiveSource, 0, key) { RoutedEvent = Keyboard.KeyDownEvent };
                InputManager.Current.ProcessInput(e1);
            }
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM