2013-09-26 29 views
0

我正在写一个小应用程序,该应用程序应显示剪贴板中当前字符串中的字符数。例如,有人突出显示一行文本并点击复制,然后运行我的应用程序。我希望它显示字符串中的字符数。应该很简单,但我一直让Zero返回。有相关的线程,但没有回答我的问题。这里是我到目前为止(它是一个控制台应用程序BTW):从剪贴板内容设置字符串值C#

using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 

namespace BuildandRun 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      string data = Clipboard.GetText(); 
      Console.WriteLine(data); 
      int dataLength = data.Length; 
      Console.WriteLine(dataLength + " Characters."); 

      Console.ReadLine(); 
     } 
    } 
} 

回答

1

MSDN

Clipboard类只能在设置为单线程 公寓线程使用(STA)模式。要使用此类,请确保您的Main方法 标有STAThreadAttribute特性。

只需更改您的代码:

[STAThreadAttribute] 
static void Main(string[] args) 
0

Clipboard仅适用于单线程单元线程。

因此答案是添加以下的Main():

[STAThread] 
static void Main(string[] args) 
{ 
    ... 

或变通方法是这样的:

public string GetClipboardText() 
{ 
    string result = ""; 

    Thread thread = new Thread(() => result = Clipboard.GetText()); 
    thread.SetApartmentState(ApartmentState.STA); 
    thread.Start(); 
    thread.Join(); 

    return result; 
} 
+0

感谢马修,@japc回答上面的伟大工程。 –