当前位置: 动力学知识库 > 问答 > 编程问答 >

Toggle monitoring clipboard in C# WinForm app

问题描述:

Currently I've an app which monitors windows clipboard. If there is any change, it displays clipboard text in a textbox. I'm using the following code found by googling-

[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;

}

}

The above code works fine. But now I would to handle it dynamically. Something like-

private void chkToggleMonitor_CheckedChanged(object sender, EventArgs e)

{

if (chkToggleMonitor.CheckState==CheckState.Checked)

{

//Monitor clipboard

}

else

{

//Don't monitor clipboard

}

}

Is there any way to do it based on the current clipboard code?

Thanks.

网友答案:

To add the application to Windows Clicpboard listener use:

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

And to remove it from the list use:

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

Eventually you can use it in your code, like this:

if (chkToggleMonitor.CheckState==CheckState.Checked)
{
    AddClipboardFormatListener(this.Handle);
}
else
{
    RemoveClipboardFormatListener(this.Handle);
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: