I have the below code which opens a webpage when a user clicks on a Windows Form. The problem: When clickedagain while the webpage is open, the application opens another instance of the webpage and so on. How can I restrict the application not to open a second webpage when the first is active? (Like in javascript window.open("","myWindow","width=200,height=100");)) Any help is greatly appreciated.

My Code:

 private void btLogin_Click(object sender, EventArgs e)
        {
            try
            {
                System.Diagnostics.Process.Start(MyLink);
            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.Message);
            }
        }
3

There are 3 answers

1
Kurubaran On BEST ANSWER

You can try the following code, Before opening the browser first we get the currently running browser processes(ex Chrome) and iterate through each process and compare the MainWindowTitle.This property holds the title of the opened browser window. If the target URL (with title) is already running then the rest of the code is ignored.

private void OpenBrowser()
{
    bool processStarted = false;

    Process[] processes = Process.GetProcesses();

    foreach (var item in processes)
    {
        if (item.MainWindowTitle.Equals("Google - Google Chrome", StringComparison.OrdinalIgnoreCase))
        {
            processStarted = true;
            break;
        }
    }

    if (!processStarted)
    {
        Process p = new Process();
        ProcessStartInfo info = new ProcessStartInfo();
        info.FileName = "chrome.exe";
        p.StartInfo = info;
        info.Arguments = "https://www.google.lk";
        p.Start();
    }
}
0
Jota WA On

You can detect if the Process has terminated or not,so,just do this:

// verify if the process has exited
if(this.process != null && this.process.HasExited)
{
        Process p = new Process();
        ProcessStartInfo info = new ProcessStartInfo();
        info.FileName = "chrome.exe";
        p.StartInfo = info;
        info.Arguments = "https://www.google.lk";
        p.Start();
        // save the process in a variable
        this.process = p;
}
1
Hozefa Laxmidhar On

If the point is to open a webpage in your application, you will have to use WebBrowser control. Put WebBrowser control on your form, and add this code to the button which is responsible for opening the site:

for example.......................

       webBrowser1.Navigate("www.google.com");