KeyPressed事件

时间:2010-04-07 06:45:30

标签: c# wpf

我的问题是我想检查箭头向上或向下键是否按下然后我想在文本框控件中增加或减少值。我已经注册了keyup事件,但我必须释放向上箭头键才能更改值,我想要的是如果用户按下向上箭头键然后它会增加值,直到用户释放向上箭头键和向下箭头键相同。有什么想法吗?

5 个答案:

答案 0 :(得分:4)

您应该参加KeyUp事件,而不是使用KeyDown事件。如果您只是按住键,也会多次发送。

答案 1 :(得分:0)

您是否尝试重新注册KeyDown事件以设置标志,然后使用KeyUp事件来取消设置标志?

答案 2 :(得分:0)

bool isIncrement = true;

keyDown执行方法:

StopWatch s = StopWatch.StartNew();
int timeInterval = 500; // for 0.5 second
i=1;
while(1)
{
    if((int)s.ElapsedMilliseconds / timeInterval < i++ )
        continue;
    if(isIncrement)
    {
        //increment value
    }
    else
    {
        s.Stop();
        return;
    }
}

keyUp执行方法:

isIncrement = false;

答案 3 :(得分:0)

你确定你只想要一个WPF的RepeatButton吗?它有这个功能

答案 4 :(得分:0)

使用此技术创建一个带向上和向下按钮的NumericTextBox。

在XAML中你有类似的东西:

<Button x:Name="bntUp"                                 
        Command="{x:Static local:IntegerTextBox.UpCommand}"
        Width="10" Grid.Row="0" Cursor="Hand"
        HorizontalAlignment="Right">
    <Button.Template>
        <ControlTemplate TargetType="Button">
            <Border Margin="1" Background="{StaticResource UpArrowBrush}" />
        </ControlTemplate>
    </Button.Template>
</Button>
<Button x:Name="bntDown"                                 
        Command="{x:Static local:IntegerTextBox.DownCommand}"
        Width="10" Grid.Row="1" Cursor="Hand"
        HorizontalAlignment="Right">
    <Button.Template>
        <ControlTemplate TargetType="Button">
            <Border Margin="1" Background="{StaticResource DownArrowBrush}" />
        </ControlTemplate>
    </Button.Template>
</Button>

在代码后面(用于向上/增加部分):

 Private Shared _UpCommand As RoutedCommand
    Private Shared _DownCommand As RoutedCommand

    Public Shared ReadOnly Property UpCommand() As RoutedCommand
        Get
            Return _UpCommand
        End Get
    End Property

    Private Shared Sub InitializeCommands()

        _UpCommand = New RoutedCommand("UpCommand", GetType(IntegerTextBox))
        CommandManager.RegisterClassCommandBinding(GetType(IntegerTextBox), New CommandBinding(_UpCommand, AddressOf OnUpCommand))
        CommandManager.RegisterClassInputBinding(GetType(IntegerTextBox), New InputBinding(_UpCommand, New KeyGesture(Key.Up)))

    End Sub

    Private Shared Sub OnUpCommand(ByVal sender As Object, ByVal e As ExecutedRoutedEventArgs)

        Dim itb As IntegerTextBox = TryCast(sender, IntegerTextBox)
        If itb Is Nothing Then Return
        itb.OnUp()

    End Sub

Protected Overridable Sub OnUp()

        Dim caretIndex As Integer = Me.CaretIndex

        Me.Value += 1

        Me.GetBindingExpression(IntegerTextBox.TextProperty).UpdateSource()

        If caretIndex <= Me.Text.Length Then Me.CaretIndex = caretIndex Else Me.CaretIndex = Me.Text.Length

    End Sub