簡體   English   中英

C#Clipboard.GetText()

[英]C# Clipboard.GetText()

如何在非靜態線程中獲取剪貼板文本? 我有一個解決方案,但我正在努力獲得最清潔/最短的方式。 正常調用時,結果會變為空字符串。

我將添加一個輔助方法,可以在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();
    }
}

嘗試將ApartmentStateAttribute添加到main方法中

[STAThread]
static void Main() {
  //my beautiful codes
}

我不知道你對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());
        }
    }
}

你不能; 您必須指定STAThread屬性

注意:

ThreadStateException

當前線程不是單線程單元(STA)模式。 STAThreadAttribute添加到應用程序的Main方法中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM