C# 控制台应用程序中剪贴板的奇怪行为 [英] Strange behaviour with clipboard in C# console application

查看:40
本文介绍了C# 控制台应用程序中剪贴板的奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个小程序:

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);
    }
}

我运行它,然后从记事本复制一个字符串.但是程序只是从剪贴板中获取一个空字符串并写入您复制了".

I run it, and I copy a string from Notepad. But the program just gets an empty string from the clipboard and writes "You copied ".

这里有什么问题?在控制台应用程序中,是否存在使剪贴板访问行为异常的原因?

What's the problem here? Is there something that makes clipboard access behave weirdly in a console application?

这是 Windows 7 SP1 x86、.NET 4 客户端配置文件.

This is Windows 7 SP1 x86, .NET 4 Client Profile.

推荐答案

使用这个功能

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;
  }

在这一行:

  Console.WriteLine("You copied " + Clipboard.GetMeText());

问题在于剪贴板仅适用于某些线程模型 (ApartmentState.STA),因此您必须创建一个新线程并为其提供该模型,此代码可以做到这一点.

The problem is that the clipboard only works with certain threading models (ApartmentState.STA) so you have to make a new thread and give it that model this code does that.

这篇关于C# 控制台应用程序中剪贴板的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆