Compartilhar via


Exemplo de formulário de declarações automáticas

O exemplo de Declarações Automáticas aborda um cenário hipotético para um assessor de seguro. O trabalho do assessor exige que ele ou ela visite com clientes em sua casa ou empresa e insira suas informações de declaração em um formulário. Para aumentar a produtividade do assessor, seu departamento de TI desenvolve um aplicativo de tablet que permite que ele insira informações de declaração de forma rápida e precisa por meio de dois controles de tinta: controles InkEdit e InkPicture .

Neste exemplo, um controle InkEdit é usado para cada campo de entrada de texto. Um usuário insere as informações relevantes sobre uma apólice de seguro e veículo nesses campos com uma caneta. O controle InkPicture é usado para adicionar tinta sobre uma imagem de automóvel para realçar áreas danificadas do automóvel. O exemplo de Declarações Automáticas está disponível para C# e Microsoft Visual Basic .NET. Este tópico descreve o .NET do Visual Basic.

A classe AutoClaims é definida como uma subclasse de System.Windows.Forms.Form e uma classe aninhada é definida para criar e gerenciar camadas de tinta para diferentes tipos de danos. Quatro manipuladores de eventos são definidos para executar as seguintes tarefas:

  • Inicializando as camadas de formulário e tinta.
  • Redesenhar o controle InkPicture .
  • Selecionando uma camada de tinta por meio da caixa de listagem.
  • Alterando a visibilidade de uma camada de tinta.

Observação

As versões deste exemplo estão disponíveis no C# e no Visual Basic .NET. A versão discutida nesta seção é o .NET do Visual Basic. Os conceitos são os mesmos entre as versões.

 

Definindo as camadas de formulário e tinta

Você precisa importar o namespace Microsoft.Ink :

Imports Microsoft.Ink
// The Ink namespace, which contains the Tablet PC Platform API
using Microsoft.Ink;

Em seguida, na Classe AutoClaims, uma classe aninhada InkLayer é definida e uma matriz de quatro InkLayer objetos é declarada. (InkLayer contém um objeto Microsoft.Ink.Ink para armazenar tinta e valores System.Drawing.Color e Boolean para armazenar a cor e o estado oculto da camada.) Um quinto objeto Ink é declarado para manipular tinta para InkPicture quando todas as camadas de tinta estão ocultas.

' Declare the array of ink layers used the vehicle illustration.
Dim inkLayers(3) As InkLayer

' Declare an empty ink object (used when we don't want to draw
' any ink).
Dim emptyInk As Ink

' Declare a value to hold the index of selected ink
Dim selectedIndex As Integer

' Declare a value to hold whether the selected ink is hidden
Dim selectedHidden As Boolean 
// Declare the array of ink layers used the vehicle illustration.
InkLayer[] inkLayers;

// Declare an empty ink object (used when we don't want to draw
// any ink).
Ink emptyInk;

// Declare a value to hold the index of selected ink
int selectedIndex = -1;

// Declare a value to hold whether the selected ink is hidden
bool selectedHidden = false;

Cada camada tem seu próprio objeto Ink . Há quatro áreas discretas de interesse na forma de declaração (corpo, janelas, pneus e faróis), portanto, quatro objetos InkLayer são usados. Um usuário pode exibir qualquer combinação de camadas ao mesmo tempo.

Inicializando as camadas de formulário e tinta

O Load manipulador de eventos inicializa o objeto Ink e os quatro InkLayer objetos .

' Initialize the empty ink
emptyInk = New Ink()

' Initialize the four different layers of ink on the vehicle diagram:  
' vehicle body, windows, tires, and headlights.
inkLayers(0) = New InkLayer(New Ink(), Color.Red, False)
inkLayers(1) = New InkLayer(New Ink(), Color.Violet, False)
inkLayers(2) = New InkLayer(New Ink(), Color.LightGreen, False)
inkLayers(3) = New InkLayer(New Ink(), Color.Aqua, False)
// Initialize the empty ink
emptyInk = new Ink();

// Initialize the four different layers of ink on the vehicle diagram:  
// vehicle body, windows, tires, and headlights.
inkLayers = new InkLayer[4];
inkLayers[0] = new InkLayer(new Ink(), Color.Red, false);
inkLayers[1] = new InkLayer(new Ink(), Color.Violet, false);
inkLayers[2] = new InkLayer(new Ink(), Color.LightGreen, false);
inkLayers[3] = new InkLayer(new Ink(), Color.Aqua, false);

Em seguida, selecione a primeira entrada (Corpo) na caixa de listagem.

' By default, select the first ink layer
lstAnnotationLayer.SelectedIndex = 0
// By default, select the first ink layer
lstAnnotationLayer.SelectedIndex = 0;

Por fim, defina a cor da tinta do controle InkPicture como a entrada da caixa de listagem selecionada no momento.

inkPictVehicle.DefaultDrawingAttributes.Color =
      inkLayers(lstAnnotationLayer.SelectedIndex).ActiveColor
inkPictVehicle.DefaultDrawingAttributes.Color = inkLayers[lstAnnotationLayer.SelectedIndex].ActiveColor;

Redesenhar o controle InkPicture

No manipulador de eventos Paint herdado do Controle InkPicture, as camadas de tinta são verificadas para determinar quais estão ocultas. Se uma camada não estiver oculta, o procedimento de evento a exibirá usando o método Draw da propriedade Renderer. Se você examinar o Pesquisador de Objetos, verá que a propriedade Microsoft.Ink.InkPicture.Renderer está definida como um objeto Microsoft.Ink.Renderer :

Private Sub inkPictVehicle_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles inkPictVehicle.Paint
    Dim layer As InkLayer

    ' Cycle through each ink layer.  If it is visible, paint it.
    ' Note that it is necessary to customize the paint
    ' behavior, since we want to hide/show different ink layers.
    For Each layer In inkLayers
        If (Not layer.Hidden) Then
            inkPictVehicle.Renderer.Draw(e.Graphics, layer.ActiveInk.Strokes)
        End If
    Next
End Sub
private void inkPictVehicle_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
    // Cycle through each ink layer.  If it is visible, paint it.
    // Note that it is necessary to customize the paint
    // behavior, since we want to hide/show different ink layers.
    foreach (InkLayer layer in inkLayers)
    {
        if (!layer.Hidden)
        {
             inkPictVehicle.Renderer.Draw(e.Graphics,layer.ActiveInk.Strokes);
        }
    }          
}

Selecionando uma camada de tinta por meio da caixa de listagem

Quando o usuário seleciona um item na caixa de listagem, o manipulador de eventos SelectedIndexChanged primeiro verifica se a seleção foi alterada e se o controle InkPicture não está coletando tinta no momento. Em seguida, ele define a cor da tinta do controle InkPicture como a cor apropriada para a camada de tinta selecionada. Além disso, ele atualiza a caixa Ocultar Camada marcar para refletir a status oculta da camada de tinta selecionada. Por fim, o método Refresh herdado do controle InkPicture é usado para exibir apenas as camadas desejadas dentro do controle.

Private Sub chHideLayer_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chHideLayer.CheckedChanged

    ' Provided that the new checked hidden value is different than
    ' the previous value...
    If (Not (chHideLayer.Checked = selectedHidden)) Then
        If (Not (inkPictVehicle.CollectingInk)) Then

            ' Update the array indicating the visibility of each ink layer
            inkLayers(lstAnnotationLayer.SelectedIndex).Hidden = chHideLayer.Checked

            ' Set the active ink object to the selected ink
            ' Note that if the current layer is not visible, empty
            ' ink is used to prevent flicker.
            inkPictVehicle.InkEnabled = False
            If (chHideLayer.Checked) Then
                inkPictVehicle.Ink = emptyInk
            Else
                inkPictVehicle.Ink = inkLayers(lstAnnotationLayer.SelectedIndex).ActiveInk
            End If

            ' Update the previous checkbox value to the current
            selectedHidden = chHideLayer.Checked

            ' If the layer is marked hidden, disable ink collection
            inkPictVehicle.InkEnabled = Not chHideLayer.Checked

            Me.Refresh()
       Else
            ' If ink collection is enabled, the active ink cannot be changed
            ' and it is necessary to restore the checkbox to its previous value.
            chHideLayer.Checked = selectedHidden
            MessageBox.Show("Cannot change visiblity while collecting ink.")
       End If
   End If
End Sub
private void lstAnnotationLayer_SelectedIndexChanged(object sender, System.EventArgs e)
{
    // Provided that the new selected index value is different than
    // the previous value...
    if (lstAnnotationLayer.SelectedIndex != selectedIndex) 
    {
        if (!inkPictVehicle.CollectingInk)
        {
            // Set the ink and visiblity of the current ink layer
            inkPictVehicle.DefaultDrawingAttributes.Color = inkLayers[lstAnnotationLayer.SelectedIndex].ActiveColor;
            chHideLayer.Checked = inkLayers[lstAnnotationLayer.SelectedIndex].Hidden;

            // Set the active ink object to the selected ink
            // Note that if the current layer is not visible, empty
            // ink is used to prevent flicker.
            inkPictVehicle.InkEnabled = false;
            inkPictVehicle.Ink = chHideLayer.Checked?emptyInk:inkLayers[lstAnnotationLayer.SelectedIndex].ActiveInk;
            inkPictVehicle.InkEnabled = !chHideLayer.Checked;
    
            selectedIndex = lstAnnotationLayer.SelectedIndex;

            this.Refresh();
        }
        else 
        {
            // If ink collection is enabled, the active ink cannot be changed
            // and it is necessary to restore the selection to its previous value.
            lstAnnotationLayer.SelectedIndex = selectedIndex;
            MessageBox.Show("Cannot change active ink while collecting ink.");
        }
    }
}

Alterando a visibilidade de uma camada de tinta

O CheckedChanged manipulador de eventos primeiro verifica se a seleção foi alterada e se o controle InkPicture não está coletando tinta no momento. Em seguida, ele atualiza a status oculta da camada de tinta selecionada, define InkEnabled do controle InkPicture como FALSE, .

Em seguida, a propriedade InkEnabled do controle InkPicture é definida como FALSE antes de atualizar sua propriedade Ink.

Por fim, o controle InkPicture está habilitado ou desabilitado para a parte específica do veículo com base em se a caixa Ocultar camada marcar está selecionada e o método Refresh do controle InkPicture é usado para exibir apenas as camadas desejadas dentro do controle.

Private Sub chHideLayer_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chHideLayer.CheckedChanged

    ' Provided that the new checked hidden value is different than
    ' the previous value...
    If (Not (chHideLayer.Checked = selectedHidden)) Then
        If (Not (inkPictVehicle.CollectingInk)) Then

            ' Update the array indicating the visibility of each ink layer
            inkLayers(lstAnnotationLayer.SelectedIndex).Hidden = chHideLayer.Checked

            ' Set the active ink object to the selected ink
            ' Note that if the current layer is not visible, empty
            ' ink is used to prevent flicker.
            inkPictVehicle.InkEnabled = False
            If (chHideLayer.Checked) Then
                inkPictVehicle.Ink = emptyInk
            Else
                inkPictVehicle.Ink = inkLayers(lstAnnotationLayer.SelectedIndex).ActiveInk
            End If

            ' Update the previous checkbox value to the current
            selectedHidden = chHideLayer.Checked

            ' If the layer is marked hidden, disable ink collection
            inkPictVehicle.InkEnabled = Not chHideLayer.Checked

            Me.Refresh()
        Else
            ' If ink collection is enabled, the active ink cannot be changed
            ' and it is necessary to restore the checkbox to its previous value.
            chHideLayer.Checked = selectedHidden
            MessageBox.Show("Cannot change visiblity while collecting ink.")
        End If
    End If
End Sub
private void chHideLayer_CheckedChanged(object sender, System.EventArgs e)
{
    // Provided that the new checked hidden value is different than
    // the previous value...
    if (chHideLayer.Checked != selectedHidden) 
    {
        if (!inkPictVehicle.CollectingInk)
        {
            // Update the array indicating the visibility of each ink layer
            inkLayers[lstAnnotationLayer.SelectedIndex].Hidden = chHideLayer.Checked;

            // Set the active ink object to the selected ink
            // Note that if the current layer is not visible, empty
            // ink is used to prevent flicker.
            inkPictVehicle.InkEnabled = false;
            inkPictVehicle.Ink = chHideLayer.Checked?emptyInk:inkLayers[lstAnnotationLayer.SelectedIndex].ActiveInk;
 
            // If the layer is marked hidden, disable ink collections
            inkPictVehicle.InkEnabled = !chHideLayer.Checked;

            // Update the previous checkbox value to reflect the current
            selectedHidden = chHideLayer.Checked;

            this.Refresh();
        }
        else 
        {
            // If ink collection is enabled, the active ink cannot be changed
            // and it is necessary to restore the checkbox to its previous value.
            chHideLayer.Checked = selectedHidden;
            MessageBox.Show("Cannot change visiblity while collecting ink.");
        }
    }
}

Fechando o formulário

No Windows Form Designer código gerado, os controles InkEdit e InkPicture são adicionados à lista de componentes do formulário quando o formulário é inicializado. Quando o formulário é fechado, os controles InkEdit e InkPicture são descartados, bem como os outros componentes do formulário, pelo método Dispose do formulário. O método Dispose do formulário também descarta os objetos Ink criados para o formulário.

Microsoft.Ink.Ink

Controle InkPicture

Controle InkEdit