从C#中的类调用函数

时间:2019-07-27 11:50:52

标签: c# cefsharp

我使用CefSharp作为图形界面,并且我想在用户按下“关闭”按钮时关闭窗口。现在,我必须从函数close();中调用函数exit();,该函数位于类CallbackObjectForJs的内部。我该怎么办?

ChromiumWebBrowser browser;
public void close()
{
    this.Close();
}
private void form2_Load(object sender, EventArgs e)
{
    browser = new ChromiumWebBrowser("www.myurl.com");
    browser.RegisterJsObject("csalert", new CallbackObjectForJs());
    this.Controls.Add(browser);
}
public class CallbackObjectForJs{
    public void alert(string msg){
        MessageBox.Show(msg);
    }
    public void exit() {
        close(); //that not works
    }
}

1 个答案:

答案 0 :(得分:1)

您不能直接使用close,但可以使用一些技巧,将实例作为CallbackObjectForJs的构造方法

ChromiumWebBrowser browser;
public void close()
{
    this.Close();
}
private void form2_Load(object sender, EventArgs e)
{
    browser = new ChromiumWebBrowser("www.myurl.com");
    browser.RegisterJsObject("csalert", new CallbackObjectForJs(this));
    this.Controls.Add(browser);
}

public class CallbackObjectForJs{

    Form _form;

    public CallbackObjectForJs(Form form){

        _form = form;
    }

    public void alert(string msg){
        MessageBox.Show(msg);
    }
    public void exit() {
        _form.close(); 
    }
}