在VB.NET组合框中捕获ctrl + V.

时间:2013-07-29 13:36:28

标签: vb.net combobox keyboard-shortcuts keyboard-events

我正在尝试删除换行符并在粘贴到comboBox之前替换为空格,因为它忽略了一行以外的任何内容。我正在尝试这个:

If e.Modifiers = Keys.Control AndAlso e.KeyValue = Keys.V Then Then
            Clipboard.SetText(Regex.Replace(Clipboard.GetText(TextDataFormat.UnicodeText), "\n", " "))
            e.Handled = True
        End If

我在KeyDown事件中执行此操作,但它能够捕获Ctrl或V,但不能同时捕获两者。我尝试了Capture CTRL+V or paste in a textbox in .NEThttp://social.msdn.microsoft.com/Forums/windows/en-US/096540f4-4ad4-4d24-ae12-cfb3e1b246f3/interceptingoverriding-paste-behavior-on-combobox但没有得到任何结果。可能是我的代码中缺少一些东西。请帮帮我。

我正在使用此Clipboard.GetText()获取所需的值。当我调试时替换(vbCrLf,“”)但我无法设置它。我尝试使用变量来设置它,但即便如此也没有变化。我还尝试清除剪贴板,然后使用保存修改后的值的变量重置。

我正在使用Winforms,我试过这个,但仍然没有改变我的剪贴板:

Private Const WM_PASTE As Integer = &H302
    Protected Overrides Sub WndProc(ByRef m As Message)
        If m.Msg = WM_PASTE Then
            Dim returnText As String = Nothing
            If (Clipboard.ContainsText()) Then
                returnText = Clipboard.GetText().Replace(vbCrLf, " ")
                Clipboard.Clear()
                Clipboard.SetText(returnText)
            End If
        End If
        MyBase.WndProc(m)
    End Sub

3 个答案:

答案 0 :(得分:0)

处理仅限键盘事件以拦截粘贴并不能解决问题,因为粘贴也可以使用鼠标或触摸界面完成。

因此,如果您正在使用WPF,那么只需将DataObject.Pasting事件处理程序添加到您的ComboBox,因此XAML中控件的定义将如下所示:

    <ComboBox Name="comboBox1" IsEditable="true" DataObject.Pasting="comboBox1_Pasting" ... />

最后,在你的代码处理它(我在这里添加一个方法到代码隐藏,这不像使用命令那样好):

    private void comboBox1_Pasting(object sender, DataObjectPastingEventArgs e)
    {
        // modify the clipboard content here
    }

如果您使用的是WinForms,请查看此处:hook on default “Paste” event of WinForms TextBox control

答案 1 :(得分:0)

这段代码对我有用:

Private Const WM_PASTE As Integer = &H302
    Protected Overrides Function ProcessCmdKey(ByRef msg As Message, keyData As Keys) As Boolean
        If keyData = (Keys.Control Or Keys.V) Or msg.Msg = WM_PASTE Then
            If (Clipboard.ContainsText()) Then
                Clipboard.SetText(Clipboard.GetText().Replace(vbCrLf, " "))
            End If
        End If
        Return MyBase.ProcessCmdKey(msg, keyData)
    End Function

答案 2 :(得分:-1)

使用keydown事件并像这样更改剪贴板

Private Sub ComboBox1_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles ComboBox1.KeyDown
    If e.KeyCode = Keys.V AndAlso (e.Modifiers And Keys.Control) <> 0 Then
        My.Computer.Clipboard.SetText(My.Computer.Clipboard.GetText().Replace(vbCrLf, " "))
    End If
End Sub

但是这个例子将改变剪贴板内容。根据需要修改它以粘贴或插入

相关问题