Cefsharp自定义提示

时间:2020-04-10 16:40:28

标签: cefsharp

如何进行自定义提示? 我尝试了下面的代码。

public static string ShowDialog(string text, string caption) {
        Form prompt = new Form() {
            Width = 500,
            Height = 150,
            FormBorderStyle = FormBorderStyle.FixedDialog,
            Text = caption,
            StartPosition = FormStartPosition.CenterScreen
        };
        Label textLabel = new Label() { Left = 50, Top = 20, Text = text };
        TextBox textBox = new TextBox() { Left = 50, Top = 50, Width = 400 };
        Button confirmation = new Button() { Text = "Ok", Left = 350, Width = 100, Top = 70, DialogResult = DialogResult.OK };
        confirmation.Click += (sender, e) => { prompt.Close(); };
        prompt.Controls.Add(textBox);
        prompt.Controls.Add(confirmation);
        prompt.Controls.Add(textLabel);
        prompt.AcceptButton = confirmation;

        return prompt.ShowDialog() == DialogResult.OK ? textBox.Text : "";
    }

然后按如下所示使用它

public bool OnJSDialog(IWebBrowser chromiumWebBrowser, IBrowser browser, string originUrl, CefJsDialogType dialogType, string messageText, string defaultPromptText, IJsDialogCallback callback, ref bool suppressMessage) {

        if(dialogType.ToString() == "Prompt") {

            //Form prompt = ShowDialogClass.ShowDialog("as", "asd");
            string promptValue = Components.ShowDialog("Test", "123");
            if (promptValue != "") {
                callback.Continue(true, promptValue);
            } else {
                callback.Continue(false, "");
            };

        };

但是我遇到了错误。

System.InvalidOperationException: 'Cross-thread operation not valid: Control '' accessed from a thread other than the thread it was created on.'

        return false;
    }

如何实现此对话框以显示自定义提示?

1 个答案:

答案 0 :(得分:0)

几个月太晚了,但是,你开始吧。 您正在尝试在另一个线程中创建一个新表单(您的提示表单)。在这种情况下,将从 IJsDialogHandler 类创建对象的 CEF 浏览器线程将位于提示消息线程之外的另一个线程上,因此您必须跨线程访问它。 你这样做的方式是“调用”(说类似“我不用担心,我知道我在做什么”)。当您使用“调用”请求见证人时,该见证人应该具有与您的提示消息框表单相同的功能,因此……在这种情况下,创建 CEF 浏览器的表单。所以代码应该是这样的

public bool OnJSDialog(IWebBrowser chromiumWebBrowser, IBrowser browser, string originUrl, CefJsDialogType dialogType, string messageText, string defaultPromptText, IJsDialogCallback callback, ref bool suppressMessage) {

    if(dialogType.ToString() == "Prompt") {
        if (ParentForm.InvokeRequired)
        {
            ParentForm.Invoke((MethodInvoker)delegate ()
            {
                string promptValue = Components.ShowDialog(messageText, "Prompt Message");
                if (promptValue != "") {
                    callback.Continue(true, promptValue);
                } else {
                    callback.Continue(false);
                }
            }
        }
        suppressMessage = false;
        return true;
    }
}
ParentForm
应更改为初始化 CEF 浏览器的表单的名称。