代码片段:通过Win32API监听和修改剪切板的内容

Imports System.Runtime.InteropServices

Public Class Form1
  '剪切板监控指针
  Dim ClipboardViewerNext As IntPtr
  '声明相关Win32API
  <DllImport("User32.dll", CharSet:=CharSet.Auto)> _
  Public Shared Function SetClipboardViewer(hWnd As IntPtr) As IntPtr
  End Function

  <DllImport("User32.dll", CharSet:=CharSet.Auto)> _
  Public Shared Function ChangeClipboardChain(hWndRemove As IntPtr, hWndNewNext As IntPtr) As Boolean
  End Function
  '注册事件
  Private Sub RegisterClipboardViewer()
    ClipboardViewerNext = SetClipboardViewer(Me.Handle)
  End Sub
  '注销事件
  Private Sub UnregisterClipboardViewer()
    ChangeClipboardChain(Me.Handle, ClipboardViewerNext)
  End Sub

  Protected Overrides Sub WndProc(ByRef m As Message)
    Select Case m.Msg
      '当剪切板内容发生变化时
      Case &H308
        '将当前焦点所在单元格内容复制到剪切板
        Clipboard.SetText(DataGridView1.CurrentCell.Value)
        Exit Select
      Case Else
        MyBase.WndProc(m)
        Exit Select
    End Select
  End Sub

  Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    '添加测试数据
    DataGridView1.Rows.Add({"aaa", "bbb", "ccc"})
    DataGridView1.Rows.Add({"aaa", "bbb", "ccc"})
  End Sub

  Private Sub DataGridView1_CellClick(sender As System.Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellClick
    RegisterClipboardViewer()
  End Sub

  Private Sub DataGridView1_Leave(sender As System.Object, e As System.EventArgs) Handles DataGridView1.Leave
    UnregisterClipboardViewer()
  End Sub
End Class