Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Linked TextBox

0.00/5 (No votes)
7 Sep 2009 1  
How to make the textbox act as a hyperlink when the Control key is pressed.

LinkedTextBox_new.jpg

Introduction

This is a short demo on how to make a textbox act as a hyperlink when the CTRL key is pressed and the control has the focus.

Background

I needed a LinkedTextBox control for a customer.

Using the code

The control has three additional properties:

  • CltrHyperLink
  • HyperLinkColor
  • HyperLinkVisitedColor

A new Event:

  • HyperLinkClicked

And a new Virtual method:

  • OnHyperLinkClicked

Setting the CtrlHyperLink property to true activates all the other properties and events.

HyperLinkColor is the color of the hyperlink when it is in the default state. HyperLinkVisitedColor is the color of the hyperlink in its visited state. Listening to the HyperLinkClicked event will result in the event being fired when the user holds down the Control key and clicks the left mouse button. OnHyperLinkClicked can be overridden if needed.

Overridding some of the features of the TextBox

protected override void OnKeyUp(KeyEventArgs e)
{
    base.OnKeyUp(e);
    FormatTextBox(false); //Set the decoration of the textbox to standard
}

protected override void OnKeyDown(KeyEventArgs e)
{
    base.OnKeyDown(e);
    FormatTextBox(e.Control);
    //if true Set the decoration of the textbox 
    //to an hyperlink else standard.
}

protected override void OnMouseClick(MouseEventArgs e)
{
    base.OnMouseClick(e);
    if (_IsHyperLink && e.Button == MouseButtons.Left)
    //If the the control is in hyperlink mode
    //and the left mouse button was clicked...
    {
        OnHyperLinkClicked(new EventArgs());
        FormatTextBox(false);
    }
}

private void FormatTextBox(bool ShowAsLink)
{
    if (!_CltrHyperLink)
    return;
    if (ShowAsLink)
    {
        Font = new Font(Font, FontStyle.Underline);
        ForeColor = (!_HyperLinkVisited ? _HyperLinkColor : 
                      _HyperLinkVisitedColor);
        Cursor = Cursors.Hand;
        _IsHyperLink = true;
    }
    else
    {
        Font = new Font(Font, FontStyle.Regular);
        ForeColor = SystemColors.WindowText;
        Cursor = Cursors.Default;
        _IsHyberLink = false;
    }
}

protected virtual void OnHyperLinkClicked(EventArgs e)
{
    _HyperLinkVisited = true;
    if (HyperLinkClicked != null)
        HyperLinkClicked(this, e);
}

History

  • 7 Sep. 2009 - First release.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here