【问题标题】:Working with clipboard for scraping HTML to collect words使用剪贴板抓取 HTML 以收集单词
【发布时间】:2013-01-26 08:40:47
【问题描述】:

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

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

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) 模式。确保您的 Main 函数上标记了 STAThreadAttribute。

上线

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

我该如何解决这个问题?

【问题讨论】:

  • 打开 Program.cs 并查看 Main 函数上是否标记了 STAThreadAttribute。此外,从 button1_Click 中删除 timer1.Tick += new EventHandler(timer1_Tick);,您不必在每次点击时都创建新的事件处理程序,只需执行一次即可。
  • 错误消息清楚地说明了您应该如何修复它。试过了吗?

标签: c# winforms html-agility-pack


【解决方案1】:

在您的Program.cs 中,您是否将[STAThread] 应用于Main 方法?

它应该看起来像这样:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-17
    • 2022-01-16
    • 2023-02-09
    • 1970-01-01
    相关资源
    最近更新 更多