Я нашел свой ответ here.
Для этого нам необходимо выпрямить 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.
}
возможно дубликат [Как отслеживать изменения содержимого буфера обмена в C#?] (Http://stackoverflow.com/questions/2226920/how-to-monitor-clipboard-content-changes-in-c) также [этот пост] (http://stackoverflow.com/questions/621577/clipboard-event-c-sharp) – TaW
@TaW вы ведете меня к моему ответу. Спасибо –