I want to write a program to monitor windows clipboard using C#. I found some post about this topic. According thread How to monitor clipboard content changes in C#? and Finding the handle to a WPF window, I write a demo using WPF. In all samples code I found, all of them are WinForm or WPF apps, and win32 api they interop with need window handle as parameters. Such as api function SetClipboardViewer(HWND hWndNewViewer)
But in my scenario, I need my program run background as a service to monitor and collect clipboard content. How to monitor clipboard without window UI?
Could you give me some suggestions? Thanks in advance.
According user1795804's suggestion, I write following test code
using System;
using System.Runtime.InteropServices;
namespace ConsoleApplication1
{
public static class User32
{
[DllImport("User32.dll")]
public static extern IntPtr OpenClipboard(IntPtr hWndNewOwner);
[DllImport("User32.dll")]
public static extern IntPtr GetClipboardData(uint uFormat);
}
class Program
{
static void Main(string[] args)
{
int result = (int)User32.OpenClipboard(new IntPtr(0));
if (result == 0)
{
Console.WriteLine("error");
}
else
{
Console.WriteLine("success");
}
int returnHandle = (int)User32.GetClipboardData(1); //CF_TEXT 1
if (returnHandle == 0)
{
Console.WriteLine("can't get text data");
}
Console.ReadKey();
}
}
}
The result is I can open clipboard and seem to get a handle to date object. But now I have two issue.
1. Although I have a handle to data object in clipboard, how can I get this data using handle? I can't find related function.
2. I need pass a proc function as callback so that it can receive message when system event raise. But I can't find counterpart in non-window app.