LinkLabel (Clase)
Actualización: Julio de 2008
Representa un control de etiqueta de Windows que puede mostrar hipervínculos.
Ensamblado: System.Windows.Forms (en System.Windows.Forms.dll)
[ComVisibleAttribute(true)] [ClassInterfaceAttribute(ClassInterfaceType.AutoDispatch)] public class LinkLabel : Label, IButtonControl
/** @attribute ComVisibleAttribute(true) */ /** @attribute ClassInterfaceAttribute(ClassInterfaceType.AutoDispatch) */ public class LinkLabel extends Label implements IButtonControl
El control ToolStripLabel reemplaza y agrega funcionalidad a los controles Label y LinkLabel. Sin embargo, los controles Label y LinkLabel se conservan por compatibilidad con versiones anteriores y para uso futuro, si lo desea.
El control LinkLabel es similar a un control Label, con la excepción de que puede mostrar un hipervínculo. En el texto del control se pueden especificar varios hipervínculos. Cada hipervínculo puede realizar una tarea distinta dentro de una aplicación. Por ejemplo, puede utilizar un hipervínculo para mostrar un sitio Web en Microsoft Internet Explorer o para cargar un archivo de registro asociado a una aplicación.
Cada hipervínculo que se muestra en el control LinkLabel es una instancia de la clase LinkLabel.Link. La clase LinkLabel.Link define información de vista, estado y ubicación del hipervínculo. Además, la propiedad LinkData de la clase LinkLabel.Link permite asociar al hipervínculo información, como, por ejemplo, una dirección URL que se va a mostrar. Cuando un usuario hace clic en un hipervínculo del control, se provoca el evento LinkClicked y el objeto LinkLabel.Link que representa el hipervínculo en el que se hizo clic se pasa como parte del objeto LinkLabelLinkClickedEventArgs que se pasa como parámetro al controlador de eventos. Puede utilizar este objeto para obtener el objeto LinkLabel.Link asociado al hipervínculo en el que el usuario hizo clic. Todos los hipervínculos contenidos en el control LinkLabel se almacenan en la instancia de la clase LinkLabel.LinkCollection para el control.
Existen dos maneras de agregar un hipervínculo al control LinkLabel. La forma más rápida es especificar un LinkArea y asignarlo a la propiedad LinkArea. De este modo, se puede especificar un solo hipervínculo en el texto del control. Para agregar varios hipervínculos, puede utilizar el método Add de la clase LinkLabel.LinkCollection mediante el acceso a la colección a través de la propiedad Links.
Cuando se crea un control LinkLabel, se agrega a LinkLabel.LinkCollection un hipervínculo predeterminado que contiene todo el texto del control LinkLabel. Para reemplazar este vínculo predeterminado, especifique una nueva área de vínculo con la propiedad LinkArea o especifique un vínculo con el método Add de LinkLabel.LinkCollection. También puede quitar el hipervínculo predeterminado utilizando el método Remove de la clase LinkLabel.LinkCollection.
La clase LinkLabel hereda la propiedad TabStop de la clase Label. La propiedad TabStop es true de forma predeterminada, siempre y cuando haya por lo menos un vínculo con una longitud mayor que cero en la colección Links. El control LinkLabel tiene un único valor TabIndex. Sin embargo, cada vínculo con una longitud mayor que cero obtiene su propia posición de tabulación, de izquierda a derecha. Para evitar la navegación por tabulación hasta el control LinkLabel, establezca la propiedad TabStop en false. Sin embargo, debe saber que, al agregar nuevos vínculos a la colección Links, la propiedad TabStop se establecerá de nuevo en true automáticamente.
LinkLabel proporciona varias propiedades que permiten definir la apariencia de los hipervínculos en el control. Las propiedades ActiveLinkColor, DisabledLinkColor, LinkColor y VisitedLinkColor definen los colores que se utilizan al mostrar un hipervínculo en distintos estados. La propiedad LinkBehavior define cómo se muestra el subrayado asociado a un hipervínculo.
En el siguiente ejemplo se muestra cómo se usa la clase LinkLabel. En el ejemplo se controla el evento LinkClicked abriendo un sitio web.
using System; using System.Drawing; using System.Windows.Forms; public class Form1 : System.Windows.Forms.Form { private System.Windows.Forms.LinkLabel linkLabel1; [STAThread] static void Main() { Application.Run(new Form1()); } public Form1() { // Create the LinkLabel. this.linkLabel1 = new System.Windows.Forms.LinkLabel(); // Configure the LinkLabel's location. this.linkLabel1.Location = new System.Drawing.Point(34, 56); // Specify that the size should be automatically determined by the content. this.linkLabel1.AutoSize = true; // Add an event handler to do something when the links are clicked. this.linkLabel1.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel1_LinkClicked); // Set the text for the LinkLabel. this.linkLabel1.Text = "Visit Microsoft"; // Set up how the form should be displayed and add the controls to the form. this.ClientSize = new System.Drawing.Size(292, 266); this.Controls.AddRange(new System.Windows.Forms.Control[] { this.linkLabel1 }); this.Text = "Simple Link Label Example"; } private void linkLabel1_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e) { // Specify that the link was visited. this.linkLabel1.LinkVisited = true; // Navigate to a URL. System.Diagnostics.Process.Start("http://www.microsoft.com"); } }
En el siguiente ejemplo se muestra cómo usar la clase LinkLabel, con varias secciones de LinkArea definidas, para mostrar una etiqueta en un formulario. En el ejemplo se muestra cómo se establecen las propiedades AutoSize, LinkBehavior, DisabledLinkColor, LinkColor y VisitedLinkColor para personalizar la apariencia de LinkLabel. El primer LinkArea se especifica mediante la propiedad LinkLabel.LinkArea. Los vínculos adicionales se agregan a LinkLabel mediante el método LinkLabel.LinkCollection.Add. En el ejemplo se controla el evento LinkClicked iniciando el explorador web para los hipervínculos y mostrando un MessageBox para los demás vínculos.
using System; using System.Drawing; using System.Windows.Forms; public class Form1 : System.Windows.Forms.Form { private System.Windows.Forms.LinkLabel linkLabel1; [STAThread] static void Main() { Application.Run(new Form1()); } public Form1() { // Create the LinkLabel. this.linkLabel1 = new System.Windows.Forms.LinkLabel(); // Configure the LinkLabel's size and location. Specify that the // size should be automatically determined by the content. this.linkLabel1.Location = new System.Drawing.Point(34, 56); this.linkLabel1.Size = new System.Drawing.Size(224, 16); this.linkLabel1.AutoSize = true; // Configure the appearance. // Set the DisabledLinkColor so that a disabled link will show up against the form's background. this.linkLabel1.DisabledLinkColor = System.Drawing.Color.Red; this.linkLabel1.VisitedLinkColor = System.Drawing.Color.Blue; this.linkLabel1.LinkBehavior = System.Windows.Forms.LinkBehavior.HoverUnderline; this.linkLabel1.LinkColor = System.Drawing.Color.Navy; this.linkLabel1.TabIndex = 0; this.linkLabel1.TabStop = true; // Add an event handler to do something when the links are clicked. this.linkLabel1.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel1_LinkClicked); // Identify what the first Link is. this.linkLabel1.LinkArea = new System.Windows.Forms.LinkArea(0, 8); // Identify that the first link is visited already. this.linkLabel1.Links[0].Visited = true; // Set the Text property to a string. this.linkLabel1.Text = "Register Online. Visit Microsoft. Visit MSN."; // Create new links using the Add method of the LinkCollection class. // Underline the appropriate words in the LinkLabel's Text property. // The words 'Register', 'Microsoft', and 'MSN' will // all be underlined and behave as hyperlinks. // First check that the Text property is long enough to accommodate // the desired hyperlinked areas. If it's not, don't add hyperlinks. if(this.linkLabel1.Text.Length >= 45) { this.linkLabel1.Links[0].LinkData = "Register"; this.linkLabel1.Links.Add(24, 9, "www.microsoft.com"); this.linkLabel1.Links.Add(42, 3, "www.msn.com"); // The second link is disabled and will appear as red. this.linkLabel1.Links[1].Enabled = false; } // Set up how the form should be displayed and add the controls to the form. this.ClientSize = new System.Drawing.Size(292, 266); this.Controls.AddRange(new System.Windows.Forms.Control[] {this.linkLabel1}); this.Text = "Link Label Example"; } private void linkLabel1_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e) { // Determine which link was clicked within the LinkLabel. this.linkLabel1.Links[linkLabel1.Links.IndexOf(e.Link)].Visited = true; // Display the appropriate link based on the value of the // LinkData property of the Link object. string target = e.Link.LinkData as string; // If the value looks like a URL, navigate to it. // Otherwise, display it in a message box. if(null != target && target.StartsWith("www")) { System.Diagnostics.Process.Start(target); } else { MessageBox.Show("Item clicked: " + target); } } }
import System.*;
import System.Drawing.*;
import System.Windows.Forms.*;
public class Form1 extends System.Windows.Forms.Form
{
private System.Windows.Forms.LinkLabel linkLabel1;
/** @attribute STAThread()
*/
public static void main(String[] args)
{
Application.Run(new Form1());
} //main
public Form1()
{
// Create the LinkLabel.
this.linkLabel1 = new System.Windows.Forms.LinkLabel();
// Configure the LinkLabel's size and location. Specify that the
// size should be automatically determined by the content.
this.linkLabel1.set_Location(new System.Drawing.Point(34, 56));
this.linkLabel1.set_Size(new System.Drawing.Size(224, 16));
this.linkLabel1.set_AutoSize(true);
// Configure the appearance.
// Set the DisabledLinkColor so that a disabled link will show up
// against the form's background.
this.linkLabel1.set_DisabledLinkColor(System.Drawing.Color.get_Red());
this.linkLabel1.set_VisitedLinkColor(System.Drawing.Color.get_Blue());
this.linkLabel1.set_LinkBehavior(
System.Windows.Forms.LinkBehavior.HoverUnderline);
this.linkLabel1.set_LinkColor(System.Drawing.Color.get_Navy());
this.linkLabel1.set_TabIndex(0);
this.linkLabel1.set_TabStop(true);
// Add an event handler to do something when the links are clicked.
this.linkLabel1.add_LinkClicked(new System.Windows.Forms.
LinkLabelLinkClickedEventHandler(this.linkLabel1_LinkClicked));
// Identify what the first Link is.
this.linkLabel1.set_LinkArea(new System.Windows.Forms.LinkArea(0, 8));
// Identify that the first link is visited already.
this.linkLabel1.get_Links().get_Item(0).set_Visited(true);
// Set the Text property to a string.
this.linkLabel1.set_Text("Register Online. Visit Microsoft."
+ " Visit MSN.");
// Create new links using the Add method of the LinkCollection class.
// Underline the appropriate words in the LinkLabel's Text property.
// The words 'Register', 'Microsoft', and 'MSN' will
// all be underlined and behave as hyperlinks.
// First check that the Text property is long enough to accommodate
// the desired hyperlinked areas. If it's not, don't add hyperlinks.
if (this.linkLabel1.get_Text().get_Length() >= 45) {
this.linkLabel1.get_Links().get_Item(0).set_LinkData("Register");
this.linkLabel1.get_Links().Add(24, 9, "www.microsoft.com");
this.linkLabel1.get_Links().Add(42, 3, "www.msn.com");
// The second link is disabled and will appear as red.
this.linkLabel1.get_Links().get_Item(1).set_Enabled(false);
}
// Set up how the form should be displayed and add the controls to
// the form.
this.set_ClientSize(new System.Drawing.Size(292, 266));
this.get_Controls().AddRange(new System.Windows.Forms.Control[] {
this.linkLabel1 });
this.set_Text("Link Label Example");
} //Form1
private void linkLabel1_LinkClicked(Object sender,
System.Windows.Forms.LinkLabelLinkClickedEventArgs e)
{
// Determine which link was clicked within the LinkLabel.
this.linkLabel1.get_Links().get_Item(linkLabel1.get_Links().
IndexOf(e.get_Link())).set_Visited(true);
// Display the appropriate link based on the value of the
// LinkData property of the Link object.
String target = (String)e.get_Link().get_LinkData();
// If the value looks like a URL, navigate to it.
// Otherwise, display it in a message box.
if (null != target && target.StartsWith("www")) {
System.Diagnostics.Process.Start(target);
}
else {
MessageBox.Show("Item clicked: " + target);
}
} //linkLabel1_LinkClicked
} //Form1
System.MarshalByRefObject
System.ComponentModel.Component
System.Windows.Forms.Control
System.Windows.Forms.Label
System.Windows.Forms.LinkLabel
Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile para Smartphone, Windows Mobile para Pocket PC
.NET Framework y .NET Compact Framework no admiten todas las versiones de cada plataforma. Para obtener una lista de las versiones compatibles, vea Requisitos de sistema de .NET Framework.
|
Fecha |
Historial |
Motivo |
|---|---|---|
|
Julio de 2008 |
Se ha agregado un párrafo acerca de la propiedad TabStop. |
Comentarios de los clientes. |
|
Julio de 2008 |
Se ha agregado un ejemplo de código simple en el que se usa el evento LinkClicked. |
Comentarios de los clientes. |