如何将html源同步到文本框?

时间:2018-03-18 21:46:03

标签: c# winforms chromium-embedded cefsharp

我已经扫描了标记[cefsharp],我问的问题是以类似的形式出现的(请重新考虑重复的问题操作)。

我无法解决我认为应该是一个简单的请求。在浏览器控件中获取页面的html源并同步与winform控件交互。

我在异步方面很弱,但设法通过我从这个标记[cefsharp]获得的几种方式来获取源代码。但是,任何与winform控件的交互都是从异步事件触发的,该事件会在任何后续方法中“锁定”,使其处于异步“模式”状态,从而进行任何winform控件交互。

示例1:

private async void Browser_LoadingStateChanged(object sender, 
                                        CefSharp.LoadingStateChangedEventArgs e)
{
    if (!e.IsLoading)
    {
        //-- WORKS, but ...
        string html = await Task.Run(Browser.GetSourceAsync);


        //-- .. when calling other methods which interact with winform controls,
        //-- I have to do so in the following way because I am not on the UI thread.
        //-- therefore every control needs a block like this
        if (InvokeRequired)
        {
            this.Invoke(new MethodInvoker(delegate
            {
                txtSource.Text = html;
            }));
        }
        else
        {
            txtSource.Text = html;
        }
    }
}

示例2: 我部分工作的另一个例子是这种方法。但是,从按钮单击调用工作,而浏览器事件不

public string GetSource()
{
    string result = null;

    if (Browser.IsBrowserInitialized && !Browser.IsDisposed && !Browser.Disposing)
    {
        Task<string> task = Browser.GetSourceAsync();
        var complete = task.ContinueWith(t =>
        {
            if (!t.IsFaulted)
            {
                result = t.Result;
            }
        }, TaskScheduler.Default);
        complete.Wait();

    }
    return result;
}

private void button1_Click(object sender, EventArgs e)
{
    //-- WORKS
    txtSource.Text = GetSource();
}

private void Browser_LoadingStateChanged(object sender, 
                                        CefSharp.LoadingStateChangedEventArgs e)
{
    if (!e.IsLoading)
    {
        //-- DOES NOT WORK. Hangs on waiting for the complete.Wait();
        //-- note: this method is not async and neither the button too.
        txtSource.Text = GetSource();
    }
}

0 个答案:

没有答案