In fact, a LinkLabel
can contain many Links
, for your requirement (can click on the background), we have to use the LinkLabel
for only 1 link because all the links have the same background area, clicking on the background area can't tell us which link is clicked. To handle clicking on each link, we handle the event LinkClicked
, but to change its behavior by allowing user to click on the whole background area, we have to handle the event Click
as normally. Add some MouseEnter
and MouseLeave
handler to change the backcolor if needed. Here is the code:
//Setup the link data for the LinkLabel
linkLabel1.Links.Add(new LinkLabel.Link() {Description = "StackOverflow", LinkData = "http://www.stackoverflow.com"});
linkLabel1.Text = "Stackoverflow";
linkLabel1.BackColor = Color.LightGray;
//Add 10px padding around the link text
linkLabel1.Padding = new Padding(10);
//Do this to change the Cursor to Hand pointer when mouse over the whole link
linkLabel1.Cursor = Cursors.Hand;
//Click event handler for your linkLabel1
private void linkLabel1_Click(object sender, EventArgs e) {
//Try showing the URL which the link refers
//we can use this info to, for example, visit the link
MessageBox.Show(linkLabel1.Links[0].LinkData.ToString());
}
//MouseEnter event handler to change the BackColor accordingly
private void linkLabel1_MouseEnter(object sender, EventArgs e) {
linkLabel1.BackColor = Color.Yellow;
}
//MouseLeave event handler to change the BackColor accordingly
private void linkLabel1_MouseLeave(object sender, EventArgs e){
linkLabel1.BackColor = Color.LightGray;
}
NOTE: By customizing this way, a Label
can replace the LinkLabel
, we just need some suitable Font
, TextAlign
, Tag
(for LinkData
) ...