LTR*_*LTR 9 .net c# console clipboard winforms
考虑这个小程序:
class Program
{
[STAThread]
static void Main(string[] args)
{
Console.WriteLine("Please copy something into the clipboard.");
WaitForClipboardChange();
Console.WriteLine("You copied " + Clipboard.GetText());
Console.ReadKey();
}
static void WaitForClipboardChange()
{
Clipboard.SetText("xxPlaceholderxx");
while (Clipboard.GetText() == "xxPlaceholderxx" &&
Clipboard.GetText().Trim() != "")
Thread.Sleep(90);
}
}
Run Code Online (Sandbox Code Playgroud)
我运行它,我从记事本复制一个字符串.但程序只是从剪贴板中获取一个空字符串并写入"您复制".
这有什么问题?是否存在使剪贴板访问在控制台应用程序中表现奇怪的东西?
这是Windows 7 SP1 x86,.NET 4 Client Profile.
Hog*_*gan 11
使用此功能
static string GetMeText()
{
string res = "starting value";
Thread staThread = new Thread(x =>
{
try
{
res = Clipboard.GetText();
}
catch (Exception ex)
{
res = ex.Message;
}
});
staThread.SetApartmentState(ApartmentState.STA);
staThread.Start();
staThread.Join();
return res;
}
Run Code Online (Sandbox Code Playgroud)
在这一行:
Console.WriteLine("You copied " + Clipboard.GetMeText());
Run Code Online (Sandbox Code Playgroud)
问题是剪贴板只适用于某些线程模型(ApartmentState.STA),因此您必须创建一个新线程并为此代码提供该模型.
我可以在.NET 4 Client Profile上重现您的代码问题,但是当我切换到.NET 4或4.5时,它按预期工作.
但是,ClipBoard.GetText()
手册说明:
使用此
ContainsText
方法确定剪贴板是否包含文本数据,然后使用此方法检索它.
我认为这是一个指示,而不是一个建议,所以,试试这个:
class Program
{
[STAThread]
static void Main(string[] args)
{
Console.WriteLine("Please copy something into the clipboard.");
WaitForClipboardChange();
Console.WriteLine("You copied " + Clipboard.GetText());
Console.ReadKey();
}
static void WaitForClipboardChange()
{
Clipboard.Clear();
while (!Clipboard.ContainsText())
Thread.Sleep(90);
}
}
Run Code Online (Sandbox Code Playgroud)
它确实显示了复制的文本,但我必须说这可以让我的系统在复制一些文本时可怕地挂起.