代码如下:using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;namespace AD
{
    class Program
    {
        static void Main(string[] args)
        {
            System.Diagnostics.Process.Start("识别.bat");            IDataObject data = Clipboard.GetDataObject();
            if (data.GetDataPresent(DataFormats.UnicodeText))
            {
                string strText = (string)data.GetData(DataFormats.UnicodeText);
             
            }
        }
    }
}红色报错:
未将对象引用设置到对象的实例。高手帮忙解答一下,谢谢~~~!!!!

解决方案 »

  1.   


    System.Diagnostics.Process.Start("识别.bat");
    IDataObject data = Clipboard.GetDataObject();if (data == null)  // 加个测试语句,判断就否为空
    {
        Console.WriteLine("is null");
        Console.ReadKey();
    }if (data.GetDataPresent(DataFormats.Text)) // 如果为空,这句出错.
    {
        string strText = (string)data.GetData(DataFormats.UnicodeText);} 
    Clipboard.GetDataObject()是WINFORM下的类,与Console 不兼容。
      

  2.   

    简单的说,你这个获取剪切板程序代码,应该在windows程序中运行,而不是控制台程序,这样就没问题了,比如: IDataObject iData = Clipboard.GetDataObject();
                if (iData.GetDataPresent(DataFormats.Text, true))
                {
                    label1.Text = iData.GetData(DataFormats.Text, true).ToString();
                }   
    如果你想知道原因,其实比较复杂,你愿意看就看看吧:是这样的,Clipboard 类用来包装系统剪贴板上的主要操作。他是Windows 窗体基础结构的一部分,在 System.Windows.Forms 命名空间中进行声明。(想必你在控制台应用程序中已经添加了这个引用,这倒是没问题)该类上的方法允许您在单个应用程序的上下文中获得并设置剪贴板的当前内容。实际你是读取了clipbrd.exe这个应用程序中的内容(可以在运行中运行这个程序)。
    由于该剪贴板是系统组件,因此表示它的 .NET Framework 类(Clipboard )只为一组低级别的 API 函数提供包装。实际上,剪贴板的 .NET Framework 实现不是基于原始 Win32 函数和消息的而是间接的通过 OLE 剪贴板协议执行操作。
    OLE 剪贴板是一组接口,旨在泛化基于 Windows 的应用程序与剪贴板之间发生的数据交换。因此下面就不多说了,你的控制台程序是无法直接访问剪切板的,必须使用windows应用程序(win 32。)当然,如果你非要在控制台使用,你就必须自己写许多代码,利用Win32 DLL 和 P/Invoke 平台用于 Win32 交互,但是这个操作会限制剪贴板只能使用几种格式。如果需要这方面的内容,再联系我吧
      

  3.   

    其实有简单的方法可以访问ClipBoard,没那么复杂,详见我的博客。
      

  4.   

    在你的Main方法上加上[STAThread]属性。测试通过。