Launch a new Windows form upon clicking an HTML button using DotNetBrowser

I attempted to open a Windows form using the DotNetBrowser control with specific HTML content as shown in the code below.

Upon clicking a button on the HTML page, I want to hide the loaded form and then display the second Windows form.

Here is the C# code that I used:

public partial class Form1 : Form
{
    private Browser browser;
    public Form1()
    {
        InitializeComponent();
        browser = BrowserFactory.Create();
        browser.FinishLoadingFrameEvent += delegate(object sender, FinishLoadingEventArgs e)
        {
            if (e.IsMainFrame)
            {
                JSValue value = browser.ExecuteJavaScriptAndReturnValue("window");
                value.AsObject().SetProperty("Account", new Form1());
            }
        };

        browser.LoadHTML(@"<!DOCTYPE html>
                                <html>
                                <head>
                                    <script type='text/javascript'>
                                          function sendFormData() {
                                            var firstNameValue = myForm.elements['firstName'].value;
                                            var lastNameValue = myForm.elements['lastName'].value;
                                            // Invoke the 'save' method of the 'Account' Java object.
                                            Account.Save(firstNameValue, lastNameValue);
                                          }
                                        </script>
                                </head>
                                <body>
                                <form name='myForm'>
                                    First name: <input type='text' name='firstName'/>
                                    <br/>
                                    Last name: <input type='text' name='lastName'/>
                                    <br/>
                                    <input type='button' value='Save' onclick='sendFormData();'/>
                                </form>
                                </body>
                                </html>");


        BrowserView browserView = new WinFormsBrowserView(browser);
        this.Controls.Add((Control)browserView.GetComponent());
    }

    public void Save(String firstName, String lastName)
    {
        string _firstname = firstName;            

        this.Hide();
        SecondForm frm = new SecondForm(firstName);
        frm.ShowDialog();

    }

The issue I am facing is that the first form containing the browser control does not hide and remains focused.

Your assistance in resolving this matter would be greatly appreciated.

Answer №1

When dealing with DotNetBrowser events, it is crucial to switch the execution to the main UI thread in order to perform any UI-related actions. Failure to do so may result in cross-thread operation exceptions or operations failing without any error messages.

If you want to hide a form in the .NET callback from JavaScript, you should wrap the call to its Hide method within BeginInvoke(). The updated code snippet will appear as follows:

public partial class Form1 : Form
{
    private Browser browser;
    public Form1()
    {
        InitializeComponent();
        browser = BrowserFactory.Create();
        browser.FinishLoadingFrameEvent += delegate (object sender, FinishLoadingEventArgs e)
        {
            if (e.IsMainFrame)
            {
                JSValue value = browser.ExecuteJavaScriptAndReturnValue("window");
                value.AsObject().SetProperty("Account", new Account(this));
            }
        };
        browser.LoadHTML(@"<!DOCTYPE html>
                            <html>
                            <head>
                                <script type='text/javascript'>
                                        function sendFormData() {
                                        var firstNameValue = myForm.elements['firstName'].value;
                                        var lastNameValue = myForm.elements['lastName'].value;
                                        // Invoke the 'save' method of the 'Account' Java object.
                                        Account.Save(firstNameValue, lastNameValue);
                                        }
                                    </script>
                            </head>
                            <body>
                            <form name='myForm'>
                                First name: <input type='text' name='firstName'/>
                                <br/>
                                Last name: <input type='text' name='lastName'/>
                                <br/>
                                <input type='button' value='Save' onclick='sendFormData();'/>
                            </form>
                            </body>
                            </html>");
        BrowserView browserView = new WinFormsBrowserView(browser);
        this.Controls.Add((Control)browserView.GetComponent());
    }
    public class Account
    {
        private Form Form;
        public Account(Form form)
        {
            this.Form = form;
        }
        public void Save(String firstName, String lastName)
        {
            string _firstname = firstName;
            Form.Invoke(new Action(() =>
            {
                Form.Hide();
            }));
            SecondForm frm = new SecondForm(firstName);
            frm.ShowDialog(); 
        }
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

experiencing difficulty in transmitting HTML content through nodemailer

I'm having trouble sending HTML-formatted text in emails using nodemailer. exports.send = function(req, res) { console.log(req.query); var mailOptions = { to: req.query.email, subject: req.query.sub, text: 'Date of Interview: ' ...

Using JavaScript, adding an element to an array results in the array returning a value of 1

When I try to push a string into an array and then return the array, I am getting unexpected result of "1". Upon closer inspection, it seems that the array is being successfully created but before returning it, only "1" is being returned. Here is the snip ...

Exporting NativeModules for npm package in React Native

I'm attempting to convert my React Native App into a node module. The issue I'm facing is that the module consists mainly of a NativeModule. Thus, my index.js file appears like this: import { NativeModules } from 'react-native'; expo ...

Enhance dynamically generated HTML using jQuery Mobile

Using jQuery Mobile version 1.2.0 I am dynamically generating HTML using JavaScript ($(selector).html(content)), adding it to the DOM, and then displaying it ($.mobile.changePage()). After that, I make an AJAX call, retrieve some data, and re-generate th ...

Utilizing AJAX to define the attributes of an object

As a beginner in OOP, I am trying to create an object using an ajax request. My goal is to retrieve 'responseArray' in JSON format and then manipulate it. function address(adres) { this.address_string = adres; var self = this; $.ajax({ typ ...

Hover shows no response

I'm having trouble with my hover effect. I want an element to only be visible when hovered over, but it's not working as expected. I've considered replacing the i tag with an a, and have also tried using both display: none and display: bloc ...

Error encountered in Next.js when defining columns for a MUI data grid

Currently, I am integrating MUI Data Grid into a Next.js app under development. While attempting to define a more intricate column structure, I encountered an error: { field: 'home_address', valueGetter: (value, row) => { retur ...

The utcParse() function in D3.js might return a null value

I am struggling to parse a date format that appears as follows: 2017-02-18T09:00:00+06:00. Currently, I am attempting to use the following format for parsing: d3.utcParse("%Y-%m-%dT%H:%M:%S+%Z");, however, it is returning null. Do you have any suggesti ...

Persisting dynamically generated table information into a multidimensional array

I've created a dynamic table and now I'm trying to extract the data from it and store it in a multidimensional array. However, I keep encountering an exception/error that says "Cannot set property of 0 to undefined". https://i.sstatic.net/W8B9j.p ...

Tips on effortlessly updating the URL of your website

Despite seeing the question asked multiple times, I still find myself struggling to understand how to modify a URL or create a new HTML page that seamlessly integrates into a website without redirecting users. I am curious about achieving the functionalit ...

What method does jQuery Validation use to configure the validation message?

A custom method was developed for the jQuery validation plugin to validate whether a given value meets the length requirements set during validation. The method is structured as follows: jQuery.validator.addMethod("exactLength", function(value, ...

Constructing a regular expression

I've been exploring JavaScript regular expressions and encountering some challenges while trying to build a larger one. Therefore, I have decided to seek help for the entire problem rather than just individual questions. What I am looking for is a re ...

Incorporate Material Design Lite and AMP into your Angular 5 project for a sleek

Looking to develop an e-commerce progressive web app using angular 5. Wondering how to incorporate AMP with angular 5 in Google Material Design Lite. If not viable, what are some alternative options worth considering? ...

`The challenge of properly handling quotation marks within quotation marks in JavaScript string literals

I am having trouble displaying text in a JavaScript tooltip Despite my efforts to escape the quotes and eliminate any line breaks, I keep encountering unterminated string literals. The specific text I want to show is: "No, we can't. This is going t ...

Tips for displaying the message "{"POWER":"ON"}" within the else if statement (this.responseText == ({"POWER":"ON"})) {

Hey everyone, I'm trying to adjust the color of a button on my webpage based on the response I receive from this.responseText. I understand the JSON response, but for some reason, I can't seem to incorporate it into my code. If anyone could lend ...

How can I retrieve text instead of HTML using jQuery.get?

I'm facing an issue where I am trying to retrieve data from another site using the code below: jQuery.ajaxSetup({ crossDomain: true, dataType: "jsonp text" }); jQuery.get(url, function(rawContent) { console.log(rawContent); }); However, ...

What is the best approach for running a database query using the value selected from a form dropdown?

Currently, my application server is ColdFusion and I am using SQL Server for the database. Within a select form element on my webpage, users can choose from a list of vehicles such as Volvo S60, BMW M6, and VW Jetta. Once a user selects a vehicle, I need ...

Searching in jquery not functioning as intended

Greetings! I'm in the process of creating a live search feature similar to what's demonstrated at this link. However, I've encountered a minor issue with this snippet of code: jQuery("#result").on("click",function(e){ var $clicked = $(e.ta ...

ng-repeat failing to display the final two divs

I'm having trouble with the following code. The second to last div inside the ng-repeat is not being rendered at all, and the last div is getting thrown out of the ng-repeat. I can't figure out what's wrong with this code. Can anyone spot th ...

Error message thrown by node express.js indicating that response headers cannot be reset once they have been sent

As a newcomer to both node and express, I may be making a silly mistake. If you want to see the complete source code, please visit: https://github.com/wa1gon/aclogGate/tree/master/server logRouter.get("/loggate/v1/listall", function(req, res) { let ...