【问题标题】:Get the origin data source with System.Windows.Clipboard?使用 System.Windows.Clipboard 获取原始数据源?
【发布时间】:2018-02-16 20:07:16
【问题描述】:

我正在使用System.Windows.Clipboard复制一些文本,我想知道是否有机会获得原始来源, 例如我从中复制它的文件,或网站,文件夹....?

谢谢

【问题讨论】:

  • 不,剪贴板不提供该信息。

标签: c# .net console clipboard


【解决方案1】:

Win32 GetClipboardOwner() 函数可用于获取最后将数据放入剪贴板的窗口句柄。

然后您可以将返回的句柄传递给GetWindowThreadProcessId() 以获取该窗口的进程 ID 和线程 ID。

回到 .Net 领域,您可以使用进程 ID 作为参数传递给 System.Diagnostics.Process.GetProcessById() 方法,以检索所需的信息。

请注意,您必须构建一个 64 位应用程序才能全面检查 64 位 过程。如果您的项目设置了 Prefer 32-bit 选项,一些 信息将不可用。

另请参阅:
How to get the process ID or name of the application that has updated the clipboard?


Windows API 声明。重载的 GetClipboardOwnerProcessID() 包装器方法返回剪贴板所有者的 ProcessID 以及它的线程 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()
    {
        uint processId = 0;
        GetWindowThreadProcessId(SafeNativeMethods.GetClipboardOwner(), out processId);
        return processId;
    }

    //Overload that returns a reference to the Thread ID
    public static uint GetClipboardOwnerProcessID(ref uint threadId)
    {
        uint processId = 0;
        threadId = GetWindowThreadProcessId(SafeNativeMethods.GetClipboardOwner(), out processId);
        return processId;
    }
}

包装器可以这样调用,如果你只需要进程 ID:

uint ClipBoadrOwnerProcessId = WinApi.GetClipboardOwnerProcessID();

或者这样,如果您还需要线程 ID:

uint ClipBoadrOwnerThreadId = 0;
uint ClipBoadrOwnerProcessId = WinApi.GetClipboardOwnerProcessID(ref ClipBoadrOwnerThreadId);

将返回值传递给Process.GetProcessById()方法:

Process ClipBoardOwnerProcess = Process.GetProcessById((int)WinApi.GetClipboardOwnerProcessID());
    
string ProcessName = ClipBoardOwnerProcess.ProcessName;
string ProcessWindowTitle = ClipBoardOwnerProcess.MainWindowTitle;
string ProcessFileName = ClipBoardOwnerProcess.MainModule.FileName;
//(...)

如果您从浏览器复制一些文本,ProcessName 将是您的浏览器的名称,ProcessFileName 将是其可执行文件的路径。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-09
    • 2016-10-16
    • 2018-10-13
    • 2010-11-24
    • 2014-08-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多