如何给"ctrl +"vb.net中按钮的快捷键 [英] How to give a "ctrl + " shortcut key for a button in vb.net

查看:141
本文介绍了如何给"ctrl +"vb.net中按钮的快捷键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在vb.net中为按钮添加"ctrl +"快捷方式.例如,当按下ctrl + s时,我需要执行保存按钮的click事件.

how to add a " ctrl + " shortcut to button in vb.net. For example I need to perform click event of save button when ctrl + s is pressed.

推荐答案

Winforms解决方案

在您的Form类中,将其 KeyPreview 属性设置为true,例如在Form构造函数中进行设置的示例,可以在此处或通过设计器进行设置:

In your Form class, set its KeyPreview property to true, example of it being set in the Form constructor, either set it here or via the Designer:

Public Sub New()
    ' This call is required by the designer.
    InitializeComponent()

    ' Add any initialization after the InitializeComponent() call.
    Me.KeyPreview = True
End Sub

然后您需要做的就是处理Form的 KeyDown 事件,如下所示:

Then all you need to do is handle the KeyDown event for the Form, like this:

Private Sub Form1_KeyDown(sender As Object, e As KeyEventArgs) Handles MyBase.KeyDown
    If (e.Control AndAlso e.KeyCode = Keys.S) Then
        Debug.Print("Call Save action here")
    End If
End Sub

WPF解决方案(不使用MVVM模式)

将此添加到您的.xaml文件

Add this to your .xaml file

<Window.Resources>
    <RoutedUICommand x:Key="SaveCommand" Text="Save" />
</Window.Resources>

<Window.CommandBindings>
    <CommandBinding Command="{StaticResource SaveCommand}" Executed="SaveAction" />
</Window.CommandBindings>

<Window.InputBindings>
    <KeyBinding Key="S" Modifiers="Ctrl" Command="{StaticResource SaveCommand}" />
</Window.InputBindings>

更改按钮定义以包括 Command ="{StaticResource SaveCommand}" ,例如:

Alter your button definition to include Command="{StaticResource SaveCommand}", for example:

<Button x:Name="Button1" Content="Save" Command="{StaticResource SaveCommand}" />

在您的代码隐藏(.xaml.vb)中,将您的函数调用保存例程,例如:

In your Code Behind (.xaml.vb) put your function to call the save routine, such as:

Private Sub SaveAction(sender As Object, e As RoutedEventArgs)
    Debug.Print("Call Save action here")
End Sub

这篇关于如何给"ctrl +"vb.net中按钮的快捷键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆