在 C# WinForm 应用中切换监视剪贴板

本文关键字:监视 剪贴板 WinForm 应用 | 更新日期: 2023-09-27 18:36:11

目前我有一个监视Windows剪贴板的应用程序。如果有任何更改,它会在文本框中显示剪贴板文本。我正在使用通过谷歌搜索找到的以下代码-

[DllImport("User32.dll")]
protected static extern int SetClipboardViewer(int hWndNewViewer);
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern bool ChangeClipboardChain(IntPtr hWndRemove, IntPtr hWndNewNext);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);
IntPtr nextClipboardViewer;       
public frmMain()
{
    InitializeComponent();
    nextClipboardViewer = (IntPtr)SetClipboardViewer((int)this.Handle);
}
protected override void WndProc(ref System.Windows.Forms.Message m)
{
    // defined in winuser.h
    const int WM_DRAWCLIPBOARD = 0x308;
    const int WM_CHANGECBCHAIN = 0x030D;
    switch (m.Msg)
    {
        case WM_DRAWCLIPBOARD:
                DisplayClipboardData();
                SendMessage(nextClipboardViewer, m.Msg, m.WParam, m.LParam);
            break;
        case WM_CHANGECBCHAIN:
            if (m.WParam == nextClipboardViewer)
                nextClipboardViewer = m.LParam;
            else
                SendMessage(nextClipboardViewer, m.Msg, m.WParam, m.LParam);
            break;
        default:
            base.WndProc(ref m);
            break;
    }
}

上面的代码工作正常。但现在我会动态处理它。像——

private void chkToggleMonitor_CheckedChanged(object sender, EventArgs e)
{
    if (chkToggleMonitor.CheckState==CheckState.Checked)
    {
        //Monitor clipboard
    }
    else
    {
        //Don't monitor clipboard
    }
}

有没有办法根据当前的剪贴板代码做到这一点?谢谢。

在 C# WinForm 应用中切换监视剪贴板

要将应用程序添加到 Windows Clicpboard 侦听器,请使用:

[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool AddClipboardFormatListener(IntPtr hwnd);

要将其从列表中删除,请使用:

[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool RemoveClipboardFormatListener(IntPtr hwnd);

最终,您可以在代码中使用它,如下所示:

if (chkToggleMonitor.CheckState==CheckState.Checked)
{
    AddClipboardFormatListener(this.Handle);
}
else
{
    RemoveClipboardFormatListener(this.Handle);
}