C# 使用剪贴板抓取HTML以收集单词

C# 使用剪贴板抓取HTML以收集单词,c#,winforms,html-agility-pack,C#,Winforms,Html Agility Pack,我在C#WinForm上有一个按钮。每当用户点击这个按钮,就意味着他已经准备好复制一个他想知道其含义的单词。然后他只是复制这个词。最后他展示了这个词的意思 为了实现这一点,我使用了一个计时器,它通过使用网站上的htmlAgility pack查找剪贴板并从剪贴板中获取单词。这是我目前的代码: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using S

我在C#WinForm上有一个按钮。每当用户点击这个按钮,就意味着他已经准备好复制一个他想知道其含义的单词。然后他只是复制这个词。最后他展示了这个词的意思

为了实现这一点,我使用了一个计时器,它通过使用网站上的htmlAgility pack查找剪贴板并从剪贴板中获取单词。这是我目前的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using HtmlAgilityPack;

namespace HtmlAgilityPack
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            timer1.Enabled = true;
            timer1.Tick += new EventHandler(timer1_Tick);
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (Clipboard.GetDataObject().GetDataPresent(DataFormats.Text))
            {
                string x = Clipboard.GetText();
                Clipboard.Clear();

                try
                {
                    HtmlWeb web = new HtmlWeb();
                    HtmlDocument doc = web.Load("http://www.bengalinux.org/cgi-bin/abhidhan/index.pl?en_word=" + x);
                    HtmlNodeCollection node = doc.DocumentNode.SelectNodes("//div[@class='dict_entry']//strong[2]");
                    foreach (HtmlNode n in node)
                    {
                        MessageBox.Show(n.InnerText);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("no");
                }
            }
        }
    }
}  
但它不起作用。有一个例外:

在进行OLE调用之前,必须将当前线程设置为单线程单元(STA)模式。确保主函数上标记了STAThreadAttribute

在线

if (Clipboard.GetDataObject().GetDataPresent(DataFormats.Text)).

如何解决此问题?

在您的
程序中.cs
您是否将
[STAThread]
应用于
主方法

它应该是这样的:

[STAThread]
static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new MainForm());
}

打开Program.cs,查看主函数上是否标记了STAThreadAttribute。另外,删除timer1.Tick+=neweventhandler(timer1\u Tick);从button1_Click开始,您不必在每次单击时都创建新的事件处理程序,只需执行一次。错误消息清楚地说明了您应该如何修复它。你试过吗?