我找到了我的答案here。
为此,我们需要 pinvoke AddClipboardFormatListener 和 RemoveClipboardFormatListener。
/// <summary>
/// Places the given window in the system-maintained clipboard format listener list.
/// </summary>
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool AddClipboardFormatListener(IntPtr hwnd);
/// <summary>
/// Removes the given window from the system-maintained clipboard format listener list.
/// </summary>
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool RemoveClipboardFormatListener(IntPtr hwnd);
/// <summary>
/// Sent when the contents of the clipboard have changed.
/// </summary>
private const int WM_CLIPBOARDUPDATE = 0x031D;
然后我们需要通过调用AddClipboardFormatListener 方法将我们的窗口添加到剪贴板格式侦听器列表中,并将我们的窗口句柄作为参数。将以下代码放在主窗口表单构造函数或其任何加载事件中。
AddClipboardFormatListener(this.Handle); // Add our window to the clipboard's format listener list.
重写 WndProc 方法,以便我们可以捕获 WM_CLIPBOARDUPDATE 何时发送。
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
if (m.Msg == WM_CLIPBOARDUPDATE)
{
IDataObject iData = Clipboard.GetDataObject(); // Clipboard's data.
if (iData.GetDataPresent(DataFormats.Text))
{
rtb1.Paste();
}
}
}
最后确保在关闭表单之前从剪贴板格式侦听器列表中删除主窗口。
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
RemoveClipboardFormatListener(this.Handle); // Remove our window from the clipboard's format listener list.
}