Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Links in c# textbox

I have a custom Jabber IM client and I'm having a problem with links. When something like http://something.com is 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?

Thanks

like image 799
beyerss Avatar asked Nov 26 '08 15:11

beyerss


2 Answers

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.

The MSDN solution launches 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.

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

// 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 article states, the DetectUrls property of the RichTextBox control is enabled by default, so any valid http/https urls will automatically appear as underlined hyperlinks.

like image 32
Lemonseed Avatar answered Oct 25 '22 23:10

Lemonseed


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.

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

like image 82
Jaime Garcia Avatar answered Oct 25 '22 22:10

Jaime Garcia