所以我正在构建一个名为“剪贴板历史记录”的工具
我的目标是,当我从任何地方复制某些内容(网络,电脑文本等)时,我想将my.computer.clipboard添加到datagridview。
一切都很好所以我只需要一个命令或识别 Ctrl + C 的东西(在pckeyboard中,不仅形成活动状态)并执行一次(Form1.DataGridView1 .Rows.Add(DateAndTime.Now,Clipboard.GetText)
Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
Dim keydata As Keys
If My.Computer.Keyboard.CtrlKeyDown AndAlso keydata.C Then
Form1.DataGridView1.Rows.Add(DateAndTime.Now, Clipboard.GetText)
End If
End Sub
谢谢你:)
答案 0 :(得分:0)
我知道没有标准的.Net库可以达到你想要的效果。通过使用Windows API函数AddClipboardFormatListener,您可以接收放置在ClipBoard上的项目的通知。
AddClipboardFormatListener需要一个Window句柄来发送通知。我使用从System.Windows.Forms.NativeWindow派生的类来监听WM_CLIPBOARDUPDATE。下面定义的这个类公开了一个名为ClipBoardDataAvailable的Event
,它也可以订阅,传递的参数是DataObject,可用于检索剪贴板内容。
Imports System.Runtime.InteropServices
Public Class ClipboardListener : Inherits NativeWindow
Implements IDisposable
Public Event ClipBoardDataAvailable(data As DataObject)
Public Sub New()
Me.CreateHandle(New CreateParams())
AddClipboardFormatListener(Me.Handle)
End Sub
Public Overrides Sub DestroyHandle()
Me.Dispose()
MyBase.DestroyHandle()
End Sub
Protected Overrides Sub WndProc(ByRef m As Message)
Const WM_CLIPBOARDUPDATE As Int32 = &H31D
If m.Msg = WM_CLIPBOARDUPDATE Then
Dim data As DataObject = CType(Clipboard.GetDataObject, DataObject)
RaiseEvent ClipBoardDataAvailable(data)
End If
MyBase.WndProc(m)
End Sub
<DllImport("user32.dll", SetLastError:=True)> _
Public Shared Function AddClipboardFormatListener(hWnd As IntPtr) As <MarshalAs(UnmanagedType.Bool)> Boolean
End Function
<DllImport("user32.dll", SetLastError:=True)> _
Public Shared Function RemoveClipboardFormatListener(hWnd As IntPtr) As <MarshalAs(UnmanagedType.Bool)> Boolean
End Function
#Region "IDisposable Support"
Private disposedValue As Boolean ' To detect redundant calls
' IDisposable
Protected Overridable Sub Dispose(disposing As Boolean)
If Not Me.disposedValue Then
RemoveClipboardFormatListener(Me.Handle)
End If
Me.disposedValue = True
End Sub
' TODO: override Finalize() only if Dispose(ByVal disposing As Boolean) above has code to free unmanaged resources.
Protected Overrides Sub Finalize()
' Do not change this code. Put cleanup code in Dispose(ByVal disposing As Boolean) above.
Dispose(False)
MyBase.Finalize()
End Sub
' This code added by Visual Basic to correctly implement the disposable pattern.
Public Sub Dispose() Implements IDisposable.Dispose
' Do not change this code. Put cleanup code in Dispose(disposing As Boolean) above.
Dispose(True)
GC.SuppressFinalize(Me)
End Sub
#End Region
End Class
示例用法:
Public Class Form1
Private WithEvents listener As New ClipboardListener
Private Sub listener_ClipBoardDataAvailable(data As DataObject) Handles listener.ClipBoardDataAvailable
If data.ContainsText Then Debug.Print(data.GetText)
End Sub
End Class