Search code examples
c#wpfawesomium

Run notepad.exe from a html-button using Awesomium


I've been looking for an example on how to open a process like notepad.exe from a html-element using WPF and Awesomium 1.7.5. The idea is that clicking a html element triggers a C# method using javascript as far as I understand the Awesomium API. However, all examples I can find refer to an earlier version that now uses obsolete functions...

Can anyone please provide me with an example on how to execute C#-code when openNotepad() is triggered?

HTML:

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>  
</head>
<body>
    <button onclick="app.openNotepad()">This button will open Notepad</button>
</body>
</html>

C#:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        webControl.Source = new Uri("index.html");
    }

    private void webControl_DocumentReady(object sender, DocumentReadyEventArgs e)
    {
        BindMethods(webControl);
    }

    private void BindMethods(IWebView _webView)
    {
        JSValue result = webControl.CreateGlobalJavascriptObject("app");
        if (result.IsObject)
        {
            JSObject appObject = result;
            appObject.Bind("openNotepad", openNotepad);
        }
    }

    private JSValue openNotepad(object obj, JavascriptMethodEventArgs jsMethodArgs)
    {
        Process.Start("notepad.exe");
        return null;
    }
}

XAML:

<Window
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:awe="http://schemas.awesomium.com/winfx" x:Class="Omega.MainWindow"
        Title="Omega" Height="350" Width="525" WindowStartupLocation="CenterScreen" WindowState="Maximized" ResizeMode="NoResize" Topmost="True" WindowStyle="None">
    <Grid>

        <awe:WebControl x:Name="webControl" DocumentReady="webControl_DocumentReady" />

    </Grid>
</Window>

Solution

  • According to Awesomium documentation to Bind and JavascriptMethodHandler, methods of handling Javascript events has changed in version 1.7.5.

    JavascriptMethodEventHandler now obsolete, and new Bind overload should be used.

    Now your code could look like

    private void BindMethods(IWebView _webView)
    {
        JSValue result = webControl.CreateGlobalJavascriptObject("app");
        if (result.IsObject)
        {
            JSObject appObject = result;
            appObject.Bind("openNotepad", openNotepad);
        }
    }
    
    private JSValue openNotepad(object obj, JavascriptMethodEventArgs jsMethodArgs)
    {
        Process.Start("notepad.exe");
        return null;
    }
    

    Note, there is example of using new overload at the end of Bind documentation page.

    Also note that javascript method in your sample actually not calling app.openNotepad() method, but alert("Run Notepad");