c#文本框中的链接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/321037/
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-03 23:07:12  来源:igfitidea点击:

Links in c# textbox

c#textboxhyperlink

提问by beyerss

I have a custom Jabber IM client and I'm having a problem with links. When something like http://something.comis entered I want it to show up as a link in the message window. The message window is a standard c# textbox. Is there a way to mark it as a link so that it can be clicked and open the webpage?

我有一个自定义 Jabber IM 客户端,但我遇到了链接问题。当输入诸如http://something.com 之类的内容时,我希望它在消息窗口中显示为链接。消息窗口是一个标准的 c# 文本框。有没有办法将其标记为链接,以便可以单击并打开网页?

Thanks

谢谢

采纳答案by Jaime Garcia

A RichTextBox can detect URL's, I don't think a regular TextBox can detect them. However you can always use a Single line RichTextBox for your input.

RichTextBox 可以检测 URL,我认为常规 TextBox 无法检测到它们。但是,您始终可以使用单行 RichTextBox 进行输入。

http://msdn.microsoft.com/en-us/library/f591a55w.aspx

http://msdn.microsoft.com/en-us/library/f591a55w.aspx

回答by Lemonseed

The solution provided by Mr Jamie Garcia is a great one, referenced by the supplied MSDN article link. However, given that this solution was proposed so long ago, I would like to propose an updated one.

Jamie Garcia 先生提供的解决方案是一个很好的解决方案,由提供的 MSDN 文章链接引用。但是,鉴于此解决方案是很久以前提出的,我想提出一个更新的解决方案。

The MSDN solutionlaunches Internet Explorer and passes the URL to the program directly. I feel a better (and more user-centered) approach would be to launch the link within the user's default web browser.

MSDN的解决方案的推出Internet Explorer和URL传递直接的程序。我觉得更好(并且更以用户为中心)的方法是在用户的默认 Web 浏览器中启动链接。

We still set up an event handler for the LinkClickedevent of our RichTextBoxcontrol, but with a few changes. Here is the complete code:

我们仍然为控件的LinkClicked事件设置了一个事件处理程序RichTextBox,但做了一些更改。这是完整的代码:

// Event raised from RichTextBox when user clicks on a link:
private void richTextBox_LinkClicked(object sender, LinkClickedEventArgs e)
{
    LaunchWeblink(e.LinkText);
}

// Performs the actual browser launch to follow link:
private void LaunchWeblink(string url)
{
    if (IsHttpURL(url)) Process.Start(url);
}

// Simple check to make sure link is valid,
// can be modified to check for other protocols:
private bool IsHttpURL(string url)
{
    return
        ((!string.IsNullOrWhiteSpace(url)) &&
        (url.ToLower().StartsWith("http")));
}

As the MSDN articlestates, the DetectUrlsproperty of the RichTextBoxcontrol is enabled by default, so any valid http/https urls will automatically appear as underlined hyperlinks.

正如MSDN 文章所述,控件的DetectUrls属性RichTextBox默认启用,因此任何有效的 http/https url 将自动显示为带下划线的超链接。