Compartir a través de


Cómo: Establecer vínculos con un objeto o página Web mediante el control LinkLabel de formularios Windows Forms

Actualización: noviembre 2007

El control LinkLabel de formularios Windows Forms permite crear vínculos de tipo Web en los formularios. Puede configurarlo de forma que cuando se haga clic en él, cambie su color para indicar que se visitó el vínculo. Para obtener más información sobre el cambio de color, vea Cómo: Cambiar la apariencia del control LinkLabel de formularios Windows Forms.

Vincular a otro formulario

Para establecer un vínculo a otro formulario con un control LinkLabel

  1. Establezca el título adecuado en la propiedad Text.

  2. Establezca la propiedad LinkArea para determinar qué parte del título se indicará como vínculo. La forma en que se indica depende de las propiedades relacionadas con la apariencia de la etiqueta del vínculo. El valor de LinkArea se representa con un objeto LinkArea que contiene dos números: la posición del carácter inicial y el número de caracteres. La propiedad LinkArea se puede establecer en la ventana Propiedades o en código de la siguiente manera:

    ' In this code example, the link area has been set to begin
    ' at the first character and extend for eight characters.
    ' You may need to modify this based on the text entered in Step 1.
    LinkLabel1.LinkArea = New LinkArea(0, 8)
    
    // In this code example, the link area has been set to begin
    // at the first character and extend for eight characters.
    // You may need to modify this based on the text entered in Step 1.
    linkLabel1.LinkArea = new LinkArea(0,8);
    
    // In this code example, the link area has been set to begin
    // at the first character and extend for eight characters.
    // You may need to modify this based on the text entered in Step 1.
    linkLabel1->LinkArea = LinkArea(0,8);
    
  3. En el controlador de eventos LinkClicked, invoque el método Show para abrir otro formulario en el proyecto y establezca la propiedad LinkVisited en true.

    Nota:

    Una instancia de la clase LinkLabelLinkClickedEventArgs lleva una referencia al control LinkLabel en el que se hizo clic, por lo que no hay necesidad de convertir el objeto sender .

    Protected Sub LinkLabel1_LinkClicked(ByVal Sender As System.Object, _
       ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) _
       Handles LinkLabel1.LinkClicked
       ' Show another form.
       Dim f2 As New Form()
       f2.Show
       LinkLabel1.LinkVisited = True
    End Sub
    
    protected void linkLabel1_LinkClicked(object sender, System. Windows.Forms.LinkLabelLinkClickedEventArgs e)
    {
       // Show another form.
       Form f2 = new Form();
       f2.Show();
       linkLabel1.LinkVisited = true;
    }
    
    private:
       void linkLabel1_LinkClicked(System::Object ^  sender,
          System::Windows::Forms::LinkLabelLinkClickedEventArgs ^  e)
       {
          // Show another form.
          Form ^ f2 = new Form();
          f2->Show();
          linkLabel1->LinkVisited = true;
       }
    

Vincular a una página Web

El control LinkLabel puede utilizarse también para mostrar una página Web con el explorador predeterminado.

Para iniciar Internet Explorer y establecer un vínculo a una página Web mediante un control LinkLabel

  1. Establezca el título adecuado en la propiedad Text.

  2. Establezca la propiedad LinkArea para determinar qué parte del título se indicará como vínculo.

  3. En el controlador de eventos LinkClicked, en medio de un bloque de control de excepciones, llame a un segundo procedimiento que establezca la propiedad LinkVisited en true y utilice el método Start para iniciar el explorador predeterminado con una dirección URL. Para utilizar el método Start, tiene que agregar una referencia al espacio de nombres System.Diagnostics.

    Nota de seguridad:

    Si el código siguiente se ejecuta en un entorno parcialmente confiable (como una unidad compartida), el compilador JIT falla cuando se llama al método VisitLink. La instrucción System.Diagnostics.Process.Start produce una solicitud de un vínculo que falla. Al capturar la excepción cuando se llama al método VisitLink, el código siguiente garantiza que, si el compilador JIT falla, el error se controla correctamente.

    Private Sub LinkLabel1_LinkClicked(ByVal sender As System.Object, _
       ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) _
       Handles LinkLabel1.LinkClicked
       Try
          VisitLink()
       Catch ex As Exception
          ' The error message
          MessageBox.Show("Unable to open link that was clicked.")
       End Try
    End Sub
    
    Sub VisitLink()
       ' Change the color of the link text by setting LinkVisited 
       ' to True.
       LinkLabel1.LinkVisited = True
       ' Call the Process.Start method to open the default browser 
       ' with a URL:
       System.Diagnostics.Process.Start("https://www.microsoft.com")
    End Sub
    
    private void linkLabel1_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e)
    {
       try
       {
          VisitLink();
       }
       catch (Exception ex )
       {
          MessageBox.Show("Unable to open link that was clicked.");
       }
    }
    
    private void VisitLink()
    {
       // Change the color of the link text by setting LinkVisited 
       // to true.
       linkLabel1.LinkVisited = true;
       //Call the Process.Start method to open the default browser 
       //with a URL:
       System.Diagnostics.Process.Start("https://www.microsoft.com");
    }
    
    private:
       void linkLabel1_LinkClicked(System::Object ^  sender,
          System::Windows::Forms::LinkLabelLinkClickedEventArgs ^  e)
       {
          try
          {
             VisitLink();
          }
          catch (Exception ^ ex)
          {
             MessageBox::Show("Unable to open link that was clicked.");
          }
       }
    private:
       void VisitLink()
       {
          // Change the color of the link text by setting LinkVisited 
          // to true.
          linkLabel1->LinkVisited = true;
          // Call the Process.Start method to open the default browser 
          // with a URL:
          System::Diagnostics::Process::Start("https://www.microsoft.com");
       }
    

Vea también

Tareas

Cómo: Cambiar la apariencia del control LinkLabel de formularios Windows Forms

Referencia

Process.Start

Información general sobre el control LinkLabel (formularios Windows Forms)

Otros recursos

LinkLabel (Control, formularios Windows Forms)