C# 如何获得打开网页的按钮?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12255697/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 22:38:56  来源:igfitidea点击:

How to get a button to open a web page?

c#visual-studio-2010

提问by Lewis Clark

I've looked everywhere, including the MSDN forums, but no one has even mentioned this or ways to do it. The basic idea is that once a Button is dragged from the toolkit, how do you then link that button to a web page, ie I have a 'Facebook' button, how do I then make it so that when the button is clicked, Facebook opens in a new browser window?

我到处找,包括 MSDN 论坛,但没有人甚至提到过这一点或这样做的方法。基本思想是,一旦从工具包中拖出一个按钮,您如何将该按钮链接到网页,即我有一个“Facebook”按钮,然后我如何制作它以便在单击该按钮时,Facebook在新的浏览器窗口中打开?

回答by Reed Copsey

Once you've dragged the button onto the designer, you can double-click on it to open up the Button's Clickevent handler. This is the code that will get run when the user clicks. You can then add the required logic, ie:

将按钮拖到设计器上后,您可以双击它以打开 Button 的Click事件处理程序。这是将在用户单击时运行的代码。然后您可以添加所需的逻辑,即:

private void button1_Click(object sender, EventArgs e)
{
    // Launch browser to facebook...
    System.Diagnostics.Process.Start("http://www.facebook.com");
}

回答by Jim O'Neil

Since you said open in a newbrowser window, I was thinking the context was an web application you were developing, so this would apply in that case:

由于您说在新的浏览器窗口中打开,我认为上下文是您正在开发的 Web 应用程序,因此这适用于这种情况:

Add an HTML button with the window.openJavaScript method. You don't need or want code-behind here because it's all happening on the client. Here's a snippet, and there are a few other options you can pass to window.opento control behavior.

使用window.openJavaScript 方法添加 HTML 按钮。您不需要或不想要代码隐藏在这里,因为这一切都发生在客户端上。这是一个片段,您可以传递一些其他选项window.open来控制行为。

        <input id="Button2" type="button" value="Facebook" onclick="window.open('http://facebook.com')"/></p>

回答by Santosh Panda

You have to use Process classunder System.dllwhich is be default added to the solution. But you should refer the namespace at the top of your class this way:

你必须使用Process classSystem.dll这是默认添加到溶液中。但是您应该以这种方式引用类顶部的命名空间:

using System;

namespace MyApplication
{
    public class MyProgram
    {
        private void button1_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("http://www.facebook.com");
        }
    }
}

回答by sujit jha

You can use Process.Start with the desired URL to open the default browser and navigate to the page:

您可以使用带有所需 URL 的 Process.Start 打开默认浏览器并导航到页面:

using system.Diagnostics;

private void button1_Click(object sender, EventArgs e)
{
    Process.Start("http://www.YouTube.com");
}