Nathaniel
Nathaniel

Reputation: 3

Read and Modify a Checkbox inside WebView2 through C# code

I have a small application in c# with an external html page that is displayed in webView2.

I want to read and modify the state of a Checkbox inside an external page displayed in WebView2 through C# code, JavaScript must be executed using WebView2's ExecuteScriptAsync function. html page inside webView2 has the following checkbox:

<input type="checkbox" id="startcheckwhenopenbox" name="startcheckwhenopenbox" checked>

The value (isAutoStartEnabled ) of the checkbox is fetched from the sqlite database. The first part does not work: if isAutoStartEnabled equals true the c# code must changes the checkbox inside webView2 to checked and if false it changes it to unchecked. The second part works: when you click on the checkbox inside webView2 it saves the value in the sqlite database. This is the important part of the code:

private void InitializeAsyncButtomButtons()
{
    string dashUrl = Path.GetFullPath(
        Path.Combine(AppContext.BaseDirectory, @"../../web/bottombuttons.html")
    );
    //MessageBox.Show(dashUrl);
    //Environment.Exit(0);
    if (File.Exists(dashUrl) && Uri.TryCreate(dashUrl, UriKind.Absolute, out Uri uri))
    {
        try
        {
            webViewBottomButtons.Source = new Uri(dashUrl);
            //webBrowser.Navigate(new Uri(dashUrl));
            //webViewBottomButtons.NavigateToString(File.ReadAllText(dashUrl)); // تحميل محتوى HTML من الملف
            //webViewBottomButtons.Source = new Uri("https://adminlte.io/themes/v3/pages/tables/simple.html");

            //await webViewBottomButtons.CoreWebView2.ExecuteScriptAsync("alert('Hello from C#');");
        }
        catch (System.UriFormatException)
        {
            return;
        }
    }
    else
    {
        //MessageBox.Show("Error loading page, please check page URL.");
    }

    webViewBottomButtons.NavigationCompleted += async (s, ee) =>
    {
        //webViewBottomButtons.CoreWebView2.OpenDevToolsWindow();

        // read autoStart value from sqlite database
        bool isAutoStartEnabled = GetAutoStartFromDatabase();
        //MessageBox.Show("isAutoStartEnabled: " + isAutoStartEnabled);

        var script =
        @"
            // التعامل مع Checkbox
            const checkbox = document.querySelector('input[name=""startcheckwhenopenbox""]');
            if (checkbox) {{
                //console.log(document.querySelector('input[name=""startcheckwhenopenbox""]'));
                //checkbox.checked = {isAutoStartEnabled.ToString().ToLower()};
                //console.log('Checkbox initialized with value: ' + checkbox.checked);
                checkbox.addEventListener('change', () => {{
                    const isChecked = checkbox.checked;
                    window.chrome.webview.postMessage(isChecked ? 'CheckboxChecked' : 'CheckboxUnchecked');
                }});
            }}

            // التعامل مع Label
            const label1 = document.querySelector('label[name=""startcheckwhenopen""]');
            if (label1) {
                label1.addEventListener('mouseover', () => {
                    window.chrome.webview.postMessage('MouseOverLabel');
                });
                label1.addEventListener('mouseout', () => {
                    window.chrome.webview.postMessage('MouseOutLabel');
                });
                label1.addEventListener('mouseleave', () => {
                    window.chrome.webview.postMessage('MouseOutLabel');
                });
                label1.addEventListener('mousedown', () => {
                    window.chrome.webview.postMessage('MouseDownLabel');
                });
                label1.addEventListener('mouseenter', () => { // تم تصحيح الحدث هنا
                    window.chrome.webview.postMessage('MouseEnterLabel');
                });
            }

        ";
        if (webViewBottomButtons.CoreWebView2 != null)
        {
            await webViewBottomButtons.CoreWebView2.ExecuteScriptAsync(script);
        }
    };

    // استقبال الرسائل من الصفحة
    webViewBottomButtons.CoreWebView2.WebMessageReceived += async (sender, args) =>
    {
        string message = args.WebMessageAsJson.Trim('"');

        switch (message)
        {
            case "MouseOverLabel":
                await Task.Delay(1000); // تأخير 1 ثانية
                ShowCustomToolTip("Start Check Process When Program Opened");
                break;

            case "MouseOutLabel":
            case "MouseLeaveLabel":
                tip.Hide(webViewBottomButtonsToolTip); // إخفاء الـ Tooltip
                break;

            case "MouseDownLabel":
            case "MouseEnterLabel":
                tip.Hide(webViewBottomButtonsToolTip); // إخفاء الـ Tooltip عند الضغط أو الدخول مرة أخرى
                break;

            case "CheckboxChecked":
                MessageBox.Show("Checkbox is checked: true");
                UpdateStartWhenOpenInDatabase(true);
                break;

            case "CheckboxUnchecked":
                MessageBox.Show("Checkbox is checked: false");
                UpdateStartWhenOpenInDatabase(false);
                break;

            default:
 
                break;
        }
    };
}

Upvotes: 0

Views: 45

Answers (0)

Related Questions