C# – Usando o InputBox no C#

Desenvolvedores que vieram no Visual Basic e migram para qualquer que seja a linguagem, normalmente sentem falta de algumas funções “tradicionais”. Isso se resolve algumas formas, e no caso dos desenvolvedores C#, o caminho mais curto seria adicionar uma referência a dll Microsoft.VisualBasic, fazendo com que todas as funções legadas da linguagem tornem disponíveis.

Mas depender de uma linguagem antiga às vezes dá um mal estar, além do fato de, sabendo de todo o poder que a nova linguagem dispõe, pra usar as funções antigas?

Pois bem, para uma necessidade extremamente simples em um dos sistemas que estive construindo, precisei coletar um dado de forma tão simples que não fazia sentido algum criar um form para isso. Nisso, antes de sair fazendo alguma coisa, decidi dar uma pesquisada na net para ver se alguém já tinha aprontado alguma coisa nesse sentido, e realmente encontrei. O código abaixo é um form que possuir as mesmas características do InputBox:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
 
namespace System
{
	/// <summary>
	/// Summary description for InputBox.
	///
	public class InputBoxDialog : System.Windows.Forms.Form
	{
 
		#region Windows Contols and Constructor
 
		private System.Windows.Forms.Label lblPrompt;
		private System.Windows.Forms.Button btnOK;
		private System.Windows.Forms.TextBox txtInput;
		/// <summary>
		/// Required designer variable.
		///
		private System.ComponentModel.Container components = null;
 
		public InputBoxDialog()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();
 
			//
			// TODO: Add any constructor code after InitializeComponent call
			//
		}
 
		#endregion
 
		#region Dispose
 
		/// <summary>
		/// Clean up any resources being used.
		///
		protected override void Dispose(bool disposing)
		{
			if (disposing)
			{
				if (components != null)
				{
					components.Dispose();
				}
			}
			base.Dispose(disposing);
		}
 
		#endregion
 
		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		///
		private void InitializeComponent()
		{
			this.lblPrompt = new System.Windows.Forms.Label();
			this.txtInput = new System.Windows.Forms.TextBox();
			this.btnOK = new System.Windows.Forms.Button();
			this.btnCancel = new System.Windows.Forms.Button();
			this.SuspendLayout();
			//
			// lblPrompt
			//
			this.lblPrompt.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
			| System.Windows.Forms.AnchorStyles.Left)
			| System.Windows.Forms.AnchorStyles.Right)));
			this.lblPrompt.BackColor = System.Drawing.SystemColors.Control;
			this.lblPrompt.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
			this.lblPrompt.Location = new System.Drawing.Point(12, 9);
			this.lblPrompt.Name = "lblPrompt";
			this.lblPrompt.Size = new System.Drawing.Size(302, 82);
			this.lblPrompt.TabIndex = 3;
			//
			// txtInput
			//
			this.txtInput.Location = new System.Drawing.Point(8, 100);
			this.txtInput.Name = "txtInput";
			this.txtInput.Size = new System.Drawing.Size(379, 20);
			this.txtInput.TabIndex = 0;
			//
			// btnOK
			//
			this.btnOK.Location = new System.Drawing.Point(320, 10);
			this.btnOK.Name = "btnOK";
			this.btnOK.Size = new System.Drawing.Size(75, 25);
			this.btnOK.TabIndex = 4;
			this.btnOK.Text = "&OK";
			this.btnOK.UseVisualStyleBackColor = true;
			this.btnOK.Click += new System.EventHandler(this.BtnOKClick);
			//
			// btnCancel
			//
			this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
			this.btnCancel.Location = new System.Drawing.Point(320, 41);
			this.btnCancel.Name = "btnCancel";
			this.btnCancel.Size = new System.Drawing.Size(75, 25);
			this.btnCancel.TabIndex = 5;
			this.btnCancel.Text = "&Cancel";
			this.btnCancel.UseVisualStyleBackColor = true;
			this.btnCancel.Click += new System.EventHandler(this.BtnCancelClick);
			//
			// InputBoxDialog
			//
			this.AcceptButton = this.btnOK;
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.BackColor = System.Drawing.SystemColors.Control;
			this.CancelButton = this.btnCancel;
			this.ClientSize = new System.Drawing.Size(398, 128);
			this.Controls.Add(this.btnCancel);
			this.Controls.Add(this.btnOK);
			this.Controls.Add(this.txtInput);
			this.Controls.Add(this.lblPrompt);
			this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
			this.MaximizeBox = false;
			this.MinimizeBox = false;
			this.Name = "InputBoxDialog";
			this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
			this.Text = "InputBox";
			this.Load += new System.EventHandler(this.InputBox_Load);
			this.ResumeLayout(false);
			this.PerformLayout();
		}
		private System.Windows.Forms.Button btnCancel;
		#endregion
 
		#region Private Variables
		string formCaption = string.Empty;
		string formPrompt = string.Empty;
		string inputResponse = string.Empty;
		string defaultValue = string.Empty;
		#endregion
 
		#region Public Properties
		public string FormCaption
		{
			get { return formCaption; }
			set { formCaption = value; }
		} // property FormCaption
		public string FormPrompt
		{
			get { return formPrompt; }
			set { formPrompt = value; }
		} // property FormPrompt
		public string InputResponse
		{
			get { return inputResponse; }
			set { inputResponse = value; }
		} // property InputResponse
		public string DefaultValue
		{
			get { return defaultValue; }
			set { defaultValue = value; }
		} // property DefaultValue
 
		#endregion
 
		#region Form and Control Events
		private void InputBox_Load(object sender, System.EventArgs e)
		{
			this.txtInput.Text = defaultValue;
			this.lblPrompt.Text = formPrompt;
			this.Text = formCaption;
			this.txtInput.SelectionStart = 0;
			this.txtInput.SelectionLength = this.txtInput.Text.Length;
			this.txtInput.Focus();
		}
		#endregion
 
		void BtnOKClick(object sender, EventArgs e)
		{
			InputResponse = this.txtInput.Text;
			this.Close();
		}
 
		void BtnCancelClick(object sender, EventArgs e)
		{
			this.Close();
		}
	}
}

Abaixo segue a função estática que permite a chamada da mesma forma que se fazia no VB:

1
2
3
4
5
6
7
8
9
10
11
public static string InputBox(string prompt,string title, string defaultValue)
{
	InputBoxDialog ib = new InputBoxDialog();
	ib.FormPrompt = prompt;
	ib.FormCaption = title;
	ib.DefaultValue = defaultValue;
	ib.ShowDialog();
	string s = ib.InputResponse;
	ib.Close();
	return s;
}

Além de resolver o problema, deu também aquele saudosismo. Bom, mesmo assim vou continuar no C#.

Referência: http://csharp.wikia.com/

Abraços

Tomás Vásquez
www.tomasvasquez.com.br

Excel 2000 – Habilitando o AutoFiltro em uma planilha protegida

Ativar o AutoFiltro em uma planilha protegida desde o Excel XP/2002 é uma tarefa simples, já que ao protegê-la, a caixa de diálogo oferecida já oferece esta possibilidade.

O problema é que os usuários do Excel 2000, que ainda são muitos não gozam desta funcionalidade. Felizmente, a Microsoft publicou um código em VBA que implementa esta funcionalidade. O código abaixo efetua a proeza:

1
2
3
4
5
6
Private Sub Workbook_Open()
    Sheet1.Protect password:="test", DrawingObjects:=True, _
        contents:=True, Scenarios:=True, _
        userinterfaceonly:=True
    Sheet1.EnableAutoFilter = True
End Sub

Resumidamente, o código efetua a proteção tradicionalmente e habilita o autofiltro logo em seguida.

A referência e código completo podem ser vistos neste link:

http://office.microsoft.com/en-us/excel/HA010982701033.aspx

Abraços

Tomás Vásquez
www.tomasvasquez.com.br

Excel VBA – Escrevendo números por extenso

Usando-se o Excel / VBA seria possível escrever-se uma função que após ler um numero na forma tradicional, o converta para forma “por extenso” ? Essa função em outras palavras, deverá ser capaz de ler um valor qualquer inteiro e escreve-lo por extenso (ex:”Quatro Mil Duzentos e Quinze”). Isso é possível ? Ficamos gratos pelo Help.

Public Function EscrevePorExtenso(ByVal n As Double) As String
    Unid = Array("", "Um", "Dois", "Três", "Quatro", "Cinco", _
                 "Seis", "Sete", "Oito", "Nove", "Dez", "Onze", "Doze", _
                 "Treze", "Quatorze", "Quinze", "Dezesseis", "Dezessete", _
                 "Dezoito", "Dezenove", "Vinte")
    Dezen = Array("", "Dez", "Vinte", "Trinta", "Quarenta", _
                  "Cinquenta", "Sessenta", "Setenta", "Oitenta", "Noventa")
    Centen = Array("", "Cento", "Duzentos", "Trezentos", _
                   "Quatrocentos", "Quinhentos", "Seiscentos", _
                   "Setecentos", "Oitocentos", "Novecentos", "Mil")
    Num = n
    Escr = ""
    If n = 0 Then
        Escr = "Zero"
    End If
    If (n \ 1000) &gt; 0 And n \ 1000 &lt; 10 Then         Escr = Unid(n \ 1000) &amp; " Mil "     End If     n = n - (n \ 1000) * 1000     If n &gt; 100 Then
        Escr = Escr &amp; Centen(n \ 100)
    End If
    If n = 100 Then
        Escr = Escr &amp; " Cem"
        GoTo Prossiga
    End If
    n = n - (n \ 100) * 100
    If n &gt;= 20 And n &lt; 100 Then         Escr = Escr &amp; " " &amp; Dezen(n \ 10)     End If     If n &gt; 0 And n &lt; 20 Then         Escr = Escr &amp; " " &amp; Unid(n)         GoTo Prossiga     End If     n = n - (n \ 10) * 10     If n &gt; 0 Then
        Escr = Escr &amp; " " &amp; Unid(n)
    End If
Prossiga:
    If Num Mod 10 &lt;&gt; 0 Then
        If InStr(1, Escr, "Vinte", 1) = 0 Then
            If InStr(1, Escr, "Trinta", 1) = 0 Then
                If InStr(1, Escr, "enta", 1) &gt; 0 Then
                    Escr = Application.Substitute(Escr, "enta", "enta e ")
                End If
            End If
        End If
    End If
    If Num Mod 10 &lt;&gt; 0 Then
        If InStr(1, Escr, "Vinte", 1) &gt; 0 Then
            If InStr(1, Escr, "Trinta", 1) = 0 Then
                If InStr(1, Escr, "enta", 1) = 0 Then
                    Escr = Application.Substitute(Escr, "Vinte", "Vinte e ")
                End If
            End If
        End If
    End If
    If Num Mod 10 &lt;&gt; 0 Then
        If InStr(1, Escr, "Vinte", 1) = 0 Then
            If InStr(1, Escr, "Trinta", 1) &gt; 0 Then
                If InStr(1, Escr, "enta", 1) = 0 Then
                    Escr = Application.Substitute(Escr, "Trinta", "Trinta e ")
                End If
            End If
        End If
    End If
    If Num Mod 100 &lt;&gt; 0 Then
        If InStr(1, Escr, "ento", 1) &gt; 0 Then
            Escr = Application.Substitute(Escr, "Cento", "Cento e ")
        End If
    End If
    If Num Mod 100 &lt;&gt; 0 Then
        If InStr(1, Escr, "entos", 1) &gt; 0 Then
            Escr = Application.Substitute(Escr, "entos", "entos e ")
        End If
    End If
    If Num Mod 1000 &lt;&gt; 0 Then
        If (Num - (Num \ 1000) * 1000) &lt;= 100 Then             If InStr(1, Escr, "Mil", 1) &gt; 0 Then
                Escr = Application.Substitute(Escr, "Mil", "Mil e ")
            End If
        End If
    End If
End Function

A função suporta números até 9999. Não é muito, mas já quebra um galho.

Bom proveito!

Fonte: BestExcel

Tomás Vásquez
www.tomasvasquez.com.br

Excel – Fórmulas matriciais

Fórmulas matriciais é um recurso do Excel pouco conhecido no qual é possível realizar cálculos múltiplos a partir de conjuntos de dados, podendo produzir um único resultado ou resultados múltiplos.

Este tipo de fórmula executa os cálculos sobre um ou mais conjuntos de dados, que são conhecidos como os argumentos da matriz. Cada argumento requer o mesmo número de linhas e colunas que os outros argumentos possuem para funcionar. Para entender o funcionamento deste tipo de fórmula confira as informações abaixo:

Exemplo

Em nosso exemplo, mostraremos como calcular a média de idade dos membros de determinada instituição com apenas uma fórmula.

Usando uma fórmula matricial você consegue fazer o cálculo de uma matriz de dados, sem a necessidade de fórmulas intermediárias. Neste caso, por exemplo, para descobrir a idade média dos membros, sem o uso de fórmulas matriciais, teríamos que efetuar o produto do número de membros para cada idade e somá-lo para depois dividir este montante pelo total de membros, como mostrado nas figuras abaixo:

Para reduzir o número de etapas e resolver este cálculo com uma só fórmula, faremos o seguinte:

  • Atribuiremos o conjunto de dados A2:A12 como a matriz 1.
  • E o conjunto de dados B2:B12 como a matriz 2.

A fórmula matricial permitirá calcular o produto de cada membro da matriz 1 (coluna A) pelo campo correspondente na matriz 2 (coluna B), e em seguida, dividir a soma deste produto pela soma total de membros (coluna B).

A fórmula usada será a seguinte:

  • {=SOMA(A2:A12*B2:B12/SOMA(B2:B12))}.

Para saber como definir os argumentos desta função, siga os passos abaixo utilizando o Assistente de função:

  • Selecione a célula B14;
  • Clique no Assistente de função, localizado na barra de fórmulas e representado pelo símbolo fx;
  • Em Categoria escolha a opção Matemática e trigonométrica;
  • Agora localize a função SOMA na lista de funções e clique em Ok;
  • Relacione os dados da planilha nos argumentos da função, como na figura abaixo:
  • Num1: A2:A12*B2:B12/SOMA(B2:B12);

Assim que tiver terminado de digitar a fórmula, pressione ao mesmo tempo as teclas CTRL+SHIFT+ENTER, para que o Excel insira as chaves {} e interprete esta fórmula como matricial.

Veja o resultado abaixo:

Esse foi apenas um exemplo com fórmulas matriciais. Tendo aprendido o conceito de como fórmula matricial trabalha você poderá elaborar cálculos complexos com facilidade.

Pratique!

Caso não consiga abrir os arquivos, clique nos links com o botão direito do mouse e escolha “salvar como”.