C#Clipboard.GetText()

Dra*_*ake 17 c# clipboard

如何在非静态线程中获取剪贴板文本?我有一个解决方案,但我正在努力获得最清洁/最短的方式.正常调用时,结果会变为空字符串.

Bit*_*KFu 14

我将添加一个辅助方法,可以在MTA主线程中将Action作为STA线程运行.我认为这可能是实现它的最简洁方法.

class Program
{
    [MTAThread]
    static void Main(string[] args)
    {
        RunAsSTAThread(
            () =>
            {
                Clipboard.SetText("Hallo");
                Console.WriteLine(Clipboard.GetText());
            });
    }

    /// <summary>
    /// Start an Action within an STA Thread
    /// </summary>
    /// <param name="goForIt"></param>
    static void RunAsSTAThread(Action goForIt)
    {
        AutoResetEvent @event = new AutoResetEvent(false);
        Thread thread = new Thread(
            () =>
            {
                goForIt();
                @event.Set();
            });
        thread.SetApartmentState(ApartmentState.STA);
        thread.Start();
        @event.WaitOne();
    }
}
Run Code Online (Sandbox Code Playgroud)


Rej*_*eri 7

尝试将ApartmentStateAttribute添加到main方法中

[STAThread]
static void Main() {
  //my beautiful codes
}
Run Code Online (Sandbox Code Playgroud)


Gab*_*abe 5

我不知道你对clean或short的定义是什么,但是如果你愿意使用完全信任,你可以只是P/Invoke本机剪贴板函数来避免线程问题.这是一个在剪贴板上打印文本的完整程序:

using System;
using System.Runtime.InteropServices;

namespace PasteText
{
    public static class Clipboard
    {
        [DllImport("user32.dll")]
        static extern IntPtr GetClipboardData(uint uFormat);
        [DllImport("user32.dll")]
        static extern bool IsClipboardFormatAvailable(uint format);
        [DllImport("user32.dll", SetLastError = true)]
        static extern bool OpenClipboard(IntPtr hWndNewOwner);
        [DllImport("user32.dll", SetLastError = true)]
        static extern bool CloseClipboard();
        [DllImport("kernel32.dll")]
        static extern IntPtr GlobalLock(IntPtr hMem);
        [DllImport("kernel32.dll")]
        static extern bool GlobalUnlock(IntPtr hMem);

        const uint CF_UNICODETEXT = 13;

        public static string GetText()
        {
            if (!IsClipboardFormatAvailable(CF_UNICODETEXT))
                return null;
            if (!OpenClipboard(IntPtr.Zero))
                return null;

            string data = null;
            var hGlobal = GetClipboardData(CF_UNICODETEXT);
            if (hGlobal != IntPtr.Zero)
            {
                var lpwcstr = GlobalLock(hGlobal);
                if (lpwcstr != IntPtr.Zero)
                {
                    data = Marshal.PtrToStringUni(lpwcstr);
                    GlobalUnlock(lpwcstr);
                }
            }
            CloseClipboard();

            return data;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(Clipboard.GetText());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)