C# 如何在 RichTextBox 中制作超链接?

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

How can I make a hyperlink work in a RichTextBox?

c#winformsrichtextbox

提问by

When I add www.stackoverflow.com into my RichTextBox and run the program it is shown in blue and as a hyperlink yet when I click it nothing happens. How can I fix this?

当我将 www.stackoverflow.com 添加到我的 RichTextBox 并运行该程序时,它以蓝色显示并作为超链接显示,但当我单击它时什么也没有发生。我怎样才能解决这个问题?

回答by Andrew Hare

Is yourTextBox.DetectUrlsset to true? We may need some more info to provide a better answer.

yourTextBox.DetectUrls设置为true?我们可能需要更多信息来提供更好的答案。

回答by aku

RichTextBox class allows you to customize its behavior when user clicks the hyperlink. Add an event handler for the RichTextBox.LinkClicked event

RichTextBox 类允许您在用户单击超链接时自定义其行为。为RichTextBox.LinkClicked事件添加事件处理程序

Process p = new Process();

private void richTextBox1_LinkClicked(object sender, LinkClickedEventArgs e)
{
   p = Process.Start("IExplore.exe", e.LinkText);
}

回答by Jeff Yates

You should make sure that DetectUrlsis set to true. If that doesn't work on its own, you may need to add a handler for the LinkClickedevent.

您应该确保将DetectUrls其设置为true。如果这本身不起作用,您可能需要为该LinkClicked事件添加一个处理程序。

回答by Sam Meldrum

  1. Make sure the text property includes a valid url. E.g. http://www.stackoverflow.com/

  2. set the DetectUrlsproperty to true

  3. Write an event handler for the LinkClickedevent.

  1. 确保 text 属性包含有效的 url。例如http://www.stackoverflow.com/

  2. DetectUrls属性设置为true

  3. LinkClicked事件编写一个事件处理程序。

Personally, I wouldn't pass "IExplore.exe"in as a parameter to the Process.Startcall as Microsoft advise as this presupposes that it is installed, and is the user's preferred browser. If you just pass the url to process start (as per below) then Windows will do the right thing and fire up the user's preferred browser with the appropriate url.

就个人而言,我不会像 Microsoft 建议的那样将“IExplore.exe”作为参数传递给Process.Start调用,因为这假定它已安装,并且是用户首选的浏览器。如果您只是将 url 传递给进程启动(如下所示),那么 Windows 将做正确的事情并使用适当的 url 启动用户的首选浏览器。

private void mRichTextBox_LinkClicked (object sender, LinkClickedEventArgs e) {
    System.Diagnostics.Process.Start(e.LinkText);
}