I am using System.Windows.Clipboard
to copy some text, and I would like to know is there a chance to get the origin source,
e.g. a the file where I copyied it from, or the website, folder.... ?
Thanks
The Win32 GetClipboardOwner() function can be used to get the Handle of the Window that last placed data into the Clipboard.
You can then pass the returned handle to GetWindowThreadProcessId() to get the Process ID and Thread ID of that Window.
Back in .NET territory, you can use the Process ID as the parameter to pass to the System.Diagnostics.Process.GetProcessById()
method, to retrieve the information needed.
Note that you have to build a 64bit application to fully inspect a 64bit process. If your project has the Prefer 32-bit option set, some information will not be available.
See also:
How to get the process ID or name of the application that has updated the clipboard?
Windows API declarations. The overloaded GetClipboardOwnerProcessID()
wrapper method returns the ProcessID
of the ClipBoard Owner and, optionally, its Thread ID.
public class WinApi
{
[DllImport("user32.dll")]
private static extern IntPtr GetClipboardOwner();
//The return value is the identifier of the thread that created the window.
[DllImport("user32.dll", SetLastError = true)]
private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
//Wrapper used to return the Window processId
public static uint GetClipboardOwnerProcessID()
{
GetWindowThreadProcessId(GetClipboardOwner(), out uint processId);
return processId;
}
//Overload that returns a reference to the Thread ID
public static uint GetClipboardOwnerProcessID(out uint threadId)
{
threadId = GetWindowThreadProcessId(GetClipboardOwner(), out uint processId);
return processId;
}
}
The wrapper can be called like this, if you just need the Process Id:
uint clipBoardOwnerProcessId = WinApi.GetClipboardOwnerProcessID();
Or this way, if you also need the Thread Id:
uint clipBoardOwnerProcessId = WinApi.GetClipboardOwnerProcessID(out uint clipBoardOwnerThreadId);
Pass the returned value to the Process.GetProcessById()
method:
Process clipBoardOwnerProcess = Process.GetProcessById((int)WinApi.GetClipboardOwnerProcessID());
string ProcessName = clipBoardOwnerProcess.ProcessName;
string ProcessWindowTitle = clipBoardOwnerProcess.MainWindowTitle;
string ProcessFileName = clipBoardOwnerProcess.MainModule.FileName;
//(...)
If you copy some text from your browser, the ProcessName
will be the name of your browser and the ProcessFileName
the path to its executable.