Compartir por


Cómo: Vincular un objeto o una página web con el control LinkLabel de formularios de Windows Forms

El control de Windows Forms LinkLabel permite crear vínculos de estilo web en el formulario. Cuando se hace clic en el vínculo, puede cambiar su color para indicar que se ha visitado el vínculo. Para obtener más información sobre cómo cambiar el color, vea Cómo: Cambiar la apariencia del control LinkLabel de Windows Forms.

Vinculación a otro formulario

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

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

    ' 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 LinkClicked controlador de eventos, invoque el método Show para abrir otro formulario en el proyecto y establezca la propiedad LinkVisited en true.

    Nota:

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

    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;
       }
    

Vinculación a una página web

El LinkLabel control también se puede usar para mostrar una página web con el explorador predeterminado.

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

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

  3. En el LinkClicked controlador de eventos, dentro de un bloque de manejo de excepciones, llama a un segundo procedimiento que establece la propiedad LinkVisited en true y utiliza el método Start para iniciar el navegador predeterminado con una dirección URL. Para usar el método Start, debe agregar una referencia al espacio de nombres System.Diagnostics.

    Importante

    Si el código siguiente se ejecuta en un entorno de confianza parcial (por ejemplo, en una unidad compartida), se produce un error en el compilador JIT cuando se llama al VisitLink método . La System.Diagnostics.Process.Start instrucción provoca un error en la demanda de vínculo. Al detectar la excepción cuando se llama al VisitLink método , el código siguiente garantiza que si se produce un error en el compilador JIT, 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("http://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("http://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("http://www.microsoft.com");
       }
    

Consulte también