简体   繁体   中英

How to get winforms to open chrome to a specified URL when the user clicks a button

I want to make an application that allows me to input a URL into a textbox and make it open chrome with that URL.

so what I need is some way to make a variable work with the private void of the button. currently I cannot get the variable to work in the private void of the button, the button has the code to open chrome with the specified URL.

Here is my code:

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;

namespace Zero_Light_Fullstack
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        string link1 = textBox1.Text;

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                Process.Start("chrome", @link1);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }

Move link1 inside of the scope of the method because you want to capture the text of the text box when the button is clicked, not when the form is instantiated.

public partial class Form1 : Form
{

public Form1()
{
    InitializeComponent();
}



private void button1_Click(object sender, EventArgs e)
{
    try
    {
        string link1 = textBox1.Text;
        Process.Start("chrome", link1);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message.ToString());
    }
}

Do you really need Chrome to open? If not, you can simply do this:

Process.Start(textBox1.Text); // It is safer to directly use the Text property

This will open the link in the default browser. If you need Chrome:

try {
    Process.Start("chrome.exe", textBox1.Text); // It is safer to directly use the Text property
} catch {
    MessageBox.Show("Chrome is not installed probably");
}

Remember to put this in the Click event.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM