Desenvolvedores.Net - TechBlog

InputBox em CSharp

0
1 Estrela2 Estrelas3 Estrelas4 Estrelas5 Estrelas (Sem votação.)
Loading...
10 de dezembro de 2010

Ola Pessoal.

Neste artigo eu vou falar de uma carência que o C# tem. O InputBox.

O C# não possui um InputBox, logo temos que criar um, aqui vai um código que facilita a vida.

Com este inputBox você pode tratar as teclas pressionadas pelo usuário, bem como modificar o título, o valor inicial, exibir uma mensagem ao usuário.

Bom, vamos deixar de falatório (ou seria escrevetório, nossa forcei agora). E vamos ao que interessa.
Vou assumir que você tem conhecimento em C#.

Crie um novo projeto to tipo Class Lybrary, isso irá criar para você uma DLL.

Na classe que veio como padrão, renomeie para InputBox.cs e utilize o código abaixo para fazer a sua DLL.

Copiar e colar amigável: http://desenvolvedores.net.pastebin.com/raw.php?i=czRKYN7F

Código:

/*
 * Exemplo de inpuBox em C#.
 * By http://desenvolvedores.net
 */
using System;
using System.Windows.Forms;

/*
 * definimos o namespace como System.Windows.Forms apenas
 * para manter no mesmo local que a MessageBox
 */
namespace System.Windows.Forms
{
    #region Formulário
    internal sealed class _InputBox : System.Windows.Forms.Form
    {
        #region Locais
        internal System.Windows.Forms.TextBox txtInput;
        private Button cmdOK;
        private Button cmdCancel;
        internal Label lblUserInfo;
        private System.ComponentModel.Container components = null;

        /// <summary>
        /// tratar os eventos de pressionamento de teclas e develver ao usuário
        /// </summary>
        internal KeyPressEventHandler keyPress = null;
        #endregion

        #region Construtor
        public _InputBox()
        {
            InitializeComponent();
            lblUserInfo.Text = "";
            txtInput.Text = "";
        }
        #endregion

        #region Métodos de criação e dipose do form
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (components != null)
                {
                    components.Dispose();
                }
            }
            base.Dispose(disposing);
        }

        private void InitializeComponent()
        {
            this.txtInput = new System.Windows.Forms.TextBox();
            this.cmdOK = new System.Windows.Forms.Button();
            this.cmdCancel = new System.Windows.Forms.Button();
            this.lblUserInfo = new System.Windows.Forms.Label();
            this.SuspendLayout();
            //
            // txtInput
            //
            this.txtInput.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.txtInput.Location = new System.Drawing.Point(16, 16);
            this.txtInput.Name = "txtInput";
            this.txtInput.Size = new System.Drawing.Size(256, 20);
            this.txtInput.TabIndex = 0;
            this.txtInput.KeyDown += new System.Windows.Forms.KeyEventHandler(this.txtInput_KeyDown);
            this.txtInput.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtInput_KeyPress);
            //
            // cmdOK
            //
            this.cmdOK.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
            this.cmdOK.Location = new System.Drawing.Point(124, 46);
            this.cmdOK.Name = "cmdOK";
            this.cmdOK.Size = new System.Drawing.Size(71, 26);
            this.cmdOK.TabIndex = 1;
            this.cmdOK.Text = "OK";
            this.cmdOK.UseVisualStyleBackColor = true;
            this.cmdOK.Click += new System.EventHandler(this.cmdOK_Click);
            //
            // cmdCancel
            //
            this.cmdCancel.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
            this.cmdCancel.Location = new System.Drawing.Point(201, 46);
            this.cmdCancel.Name = "cmdCancel";
            this.cmdCancel.Size = new System.Drawing.Size(71, 26);
            this.cmdCancel.TabIndex = 2;
            this.cmdCancel.Text = "Cancelar";
            this.cmdCancel.UseVisualStyleBackColor = true;
            this.cmdCancel.Click += new System.EventHandler(this.cmdCancel_Click);
            //
            // lblUserInfo
            //
            this.lblUserInfo.AutoSize = true;
            this.lblUserInfo.Location = new System.Drawing.Point(16, 0);
            this.lblUserInfo.MaximumSize = new System.Drawing.Size(256, 0);
            this.lblUserInfo.Name = "lblUserInfo";
            this.lblUserInfo.Size = new System.Drawing.Size(140, 13);
            this.lblUserInfo.TabIndex = 3;
            this.lblUserInfo.Text = "XXXXXXXXXXXXXXXXXXX";
            //
            // _InputBox
            //
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(292, 73);
            this.ControlBox = false;
            this.Controls.Add(this.lblUserInfo);
            this.Controls.Add(this.cmdCancel);
            this.Controls.Add(this.cmdOK);
            this.Controls.Add(this.txtInput);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
            this.Name = "_InputBox";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "InputBox";
            this.TopMost = true;
            this.Shown += new System.EventHandler(this._InputBox_Shown);
            this.ResumeLayout(false);
            this.PerformLayout();

        }
        #endregion

        #region Método Show
        public new string Show()
        {
            base.ShowDialog();
            return this.txtInput.Text;
        }
        #endregion

        #region Tratamento das ações do usuário
        private void txtInput_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                cmdOK.PerformClick();
            else if (e.KeyCode == Keys.Escape)
                cmdCancel.PerformClick();
        }

        private void cmdCancel_Click(object sender, EventArgs e)
        {
            txtInput.Text = "";
            this.Close();
        }

        private void cmdOK_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void _InputBox_Shown(object sender, EventArgs e)
        {
            //aqui temos que redimensionar o form por causa do tamanho da Label

            txtInput.Top = lblUserInfo.Top + lblUserInfo.Height + 5;
            this.Height = txtInput.Top + txtInput.Height + 60;
        }

        private void txtInput_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (keyPress != null)
                keyPress.Invoke(sender, e);
        }
        #endregion

    }
    #endregion

    #region Classe InputBox
    public static class InputBox
    {
        #region Métodos Show
        /// <summary>
        /// Exibe a inputbox
        /// </summary>
        /// <returns>string digitada</returns>
        public static string Show()
        {
            return InputBox.Show("", "", "", null);
        }

        /// <summary>
        /// Exibe a inputbox
        /// </summary>
        /// <param name="Title">Título desejado</param>
        /// <param name="keyHandler">Delegate tipo KeyPressEventHandler para capturar as teclas pressionadas</param>
        /// <returns>string digitada</returns>
        public static string Show(string Title, KeyPressEventHandler keyHandler)
        {
            return InputBox.Show(Title, "", "", keyHandler);
        }

        /// <summary>
        /// Exibe a inputbox
        /// </summary>
        /// <param name="keyHandler">Delegate tipo KeyPressEventHandler para capturar as teclas pressionadas</param>
        /// <returns>string digitada</returns>
        public static string Show(KeyPressEventHandler keyHandler)
        {
            return InputBox.Show("", "", "", keyHandler);
        }

        /// <summary>
        /// Exibe a inputbox
        /// </summary>
        /// <param name="initalValue">Valor inicial da inputBox</param>
        /// <param name="keyHandler">Delegate tipo KeyPressEventHandler para capturar as teclas pressionadas</param>
        /// <returns>string digitada</returns>
        public static string Show(KeyPressEventHandler keyHandler, string initalValue)
        {
            return InputBox.Show("", "", initalValue, keyHandler);
        }

        /// <summary>
        /// Exibe a inputbox
        /// </summary>
        /// <param name="userInfo">Mensagem inicial</param>
        /// <param name="initalValue">Valor inicial da inputBox</param>
        /// <param name="keyHandler">Delegate tipo KeyPressEventHandler para capturar as teclas pressionadas</param>
        /// <returns>string digitada</returns>
        public static string Show(string userInfo, string initalValue, KeyPressEventHandler keyHandler)
        {
            return InputBox.Show("", userInfo, initalValue, keyHandler);
        }

        /// <summary>
        /// Exibe a inputbox
        /// </summary>
        /// <param name="Title">Título desejado</param>
        /// <param name="userInfo">Mensagem inicial</param>
        /// <param name="initalValue">Valor inicial da inputBox</param>
        /// <param name="keyHandler">Delegate tipo KeyPressEventHandler para capturar as teclas pressionadas</param>
        /// <returns>string digitada</returns>
        public static string Show(KeyPressEventHandler keyHandler, string Title, string userInfo)
        {
            return InputBox.Show(Title, userInfo, "", keyHandler);
        }

        /// <summary>
        /// Exibe a inputbox
        /// </summary>
        /// <param name="Title">Título desejado</param>
        /// <param name="userInfo">Mensagem inicial</param>
        /// <param name="initalValue">Valor inicial da inputBox</param>
        /// <returns>string digitada</returns>
        public static string Show(string Title, string userInfo, string initalValue)
        {
            return InputBox.Show(Title, userInfo, initalValue, null);
        }

        /// <summary>
        /// Exibe a inputbox
        /// </summary>
        /// <param name="Title">Título desejado</param>
        /// <param name="userInfo">Mensagem inicial</param>
        /// <returns>string digitada</returns>
        public static string Show(string Title, string userInfo)
        {
            return InputBox.Show(Title, userInfo, "", null);
        }

        /// <summary>
        /// Exibe a inputbox
        /// </summary>
        /// <param name="Title">Título desejado</param>
        /// <param name="userInfo">Mensagem inicial</param>
        /// <param name="initalValue">Valor inicial da inputBox</param>
        /// <param name="keyHandler">Delegate tipo KeyPressEventHandler para capturar as teclas pressionadas</param>
        /// <returns>string digitada</returns>
        public static string Show(string Title, string userInfo, string initalValue, KeyPressEventHandler keyHandler)
        {
            using (_InputBox input = new _InputBox())
            {
                input.Text = string.IsNullOrEmpty(Title) ? "Infome um valor..." : Title;
                input.lblUserInfo.Text = userInfo;
                input.txtInput.Text = initalValue;
                if (keyHandler != null) input.keyPress = keyHandler;
                return input.Show();
            }
        }
        #endregion
    }
    #endregion
}

Exmplo de uso:
Adicione um novo projeto à sua solução do tipo Windows Forms Application
Faça referência a sua DLL.

Copiar e colar amigável: http://desenvolvedores.net.pastebin.com/raw.php?i=HqxqLyTT

/*
 * Exemplo de uso InputBox C#
 * by http://desenvolvedores.net
 */
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace InputBoxExample
{
    public class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
        }
        private void btnComHandler_Click(object sender, EventArgs e)
        {
            KeyPressEventHandler keyPress = new KeyPressEventHandler(InputBoxKeyPress);
            txtTeclaPressionada.Text = "";
            MessageBox.Show(InputBox.Show(keyPress, "Digite alguma coisa", "O que você digitar aqui irá aparecer na caixa de texto do formulário."));
        }
        private void InputBoxKeyPress(object sender, KeyPressEventArgs e)
        {
            txtTeclaPressionada.Text += e.KeyChar;
        }
        private void btnApenasTestar_Click(object sender, EventArgs e)
        {
            txtApenasTestar.Text = InputBox.Show();
        }
        private void btnValorInicial_Click(object sender, EventArgs e)
        {
            MessageBox.Show(InputBox.Show("Digite alguma coisa", "O que você digitou no textbox irá aparecer no textBox abaixo.", txtValorInicial.Text));
        }
        #region Componentes
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }
        #region Windows Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.btnComHandler = new System.Windows.Forms.Button();
            this.lblTeclaPressionada = new System.Windows.Forms.Label();
            this.txtTeclaPressionada = new System.Windows.Forms.TextBox();
            this.btnApenasTestar = new System.Windows.Forms.Button();
            this.groupBox1 = new System.Windows.Forms.GroupBox();
            this.groupBox2 = new System.Windows.Forms.GroupBox();
            this.label1 = new System.Windows.Forms.Label();
            this.txtApenasTestar = new System.Windows.Forms.TextBox();
            this.groupBox3 = new System.Windows.Forms.GroupBox();
            this.label2 = new System.Windows.Forms.Label();
            this.txtValorInicial = new System.Windows.Forms.TextBox();
            this.btnValorInicial = new System.Windows.Forms.Button();
            this.groupBox1.SuspendLayout();
            this.groupBox2.SuspendLayout();
            this.groupBox3.SuspendLayout();
            this.SuspendLayout();
            //
            // btnComHandler
            //
            this.btnComHandler.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btnComHandler.Location = new System.Drawing.Point(249, 43);
            this.btnComHandler.Name = "btnComHandler";
            this.btnComHandler.Size = new System.Drawing.Size(250, 32);
            this.btnComHandler.TabIndex = 2;
            this.btnComHandler.Text = "Testar capturando a tecla pressionada";
            this.btnComHandler.UseVisualStyleBackColor = true;
            this.btnComHandler.Click += new System.EventHandler(this.btnComHandler_Click);
            //
            // lblTeclaPressionada
            //
            this.lblTeclaPressionada.AutoSize = true;
            this.lblTeclaPressionada.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.lblTeclaPressionada.Location = new System.Drawing.Point(6, 19);
            this.lblTeclaPressionada.Name = "lblTeclaPressionada";
            this.lblTeclaPressionada.Size = new System.Drawing.Size(108, 13);
            this.lblTeclaPressionada.TabIndex = 0;
            this.lblTeclaPressionada.Text = "Teclas Pressionadas:";
            //
            // txtTeclaPressionada
            //
            this.txtTeclaPressionada.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.txtTeclaPressionada.Location = new System.Drawing.Point(120, 17);
            this.txtTeclaPressionada.Name = "txtTeclaPressionada";
            this.txtTeclaPressionada.Size = new System.Drawing.Size(379, 20);
            this.txtTeclaPressionada.TabIndex = 1;
            //
            // btnApenasTestar
            //
            this.btnApenasTestar.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btnApenasTestar.Location = new System.Drawing.Point(249, 53);
            this.btnApenasTestar.Name = "btnApenasTestar";
            this.btnApenasTestar.Size = new System.Drawing.Size(250, 32);
            this.btnApenasTestar.TabIndex = 2;
            this.btnApenasTestar.Text = "Apenas Testar";
            this.btnApenasTestar.UseVisualStyleBackColor = true;
            this.btnApenasTestar.Click += new System.EventHandler(this.btnApenasTestar_Click);
            //
            // groupBox1
            //
            this.groupBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.groupBox1.Controls.Add(this.btnComHandler);
            this.groupBox1.Controls.Add(this.lblTeclaPressionada);
            this.groupBox1.Controls.Add(this.txtTeclaPressionada);
            this.groupBox1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.groupBox1.Location = new System.Drawing.Point(12, 12);
            this.groupBox1.Name = "groupBox1";
            this.groupBox1.Size = new System.Drawing.Size(511, 91);
            this.groupBox1.TabIndex = 0;
            this.groupBox1.TabStop = false;
            this.groupBox1.Text = "Capturando as Teclas";
            //
            // groupBox2
            //
            this.groupBox2.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.groupBox2.Controls.Add(this.label1);
            this.groupBox2.Controls.Add(this.txtApenasTestar);
            this.groupBox2.Controls.Add(this.btnApenasTestar);
            this.groupBox2.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.groupBox2.Location = new System.Drawing.Point(12, 129);
            this.groupBox2.Name = "groupBox2";
            this.groupBox2.Size = new System.Drawing.Size(511, 91);
            this.groupBox2.TabIndex = 1;
            this.groupBox2.TabStop = false;
            this.groupBox2.Text = "Apenas Testar";
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label1.Location = new System.Drawing.Point(6, 21);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(48, 13);
            this.label1.TabIndex = 0;
            this.label1.Text = "Retorno:";
            //
            // txtApenasTestar
            //
            this.txtApenasTestar.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.txtApenasTestar.Location = new System.Drawing.Point(120, 19);
            this.txtApenasTestar.Name = "txtApenasTestar";
            this.txtApenasTestar.Size = new System.Drawing.Size(379, 20);
            this.txtApenasTestar.TabIndex = 1;
            //
            // groupBox3
            //
            this.groupBox3.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.groupBox3.Controls.Add(this.label2);
            this.groupBox3.Controls.Add(this.txtValorInicial);
            this.groupBox3.Controls.Add(this.btnValorInicial);
            this.groupBox3.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.groupBox3.Location = new System.Drawing.Point(12, 237);
            this.groupBox3.Name = "groupBox3";
            this.groupBox3.Size = new System.Drawing.Size(511, 91);
            this.groupBox3.TabIndex = 2;
            this.groupBox3.TabStop = false;
            this.groupBox3.Text = "Valor Inicial";
            //
            // label2
            //
            this.label2.AutoSize = true;
            this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label2.Location = new System.Drawing.Point(6, 21);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(99, 13);
            this.label2.TabIndex = 0;
            this.label2.Text = "Digite o valor Inicial";
            //
            // txtValorInicial
            //
            this.txtValorInicial.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.txtValorInicial.Location = new System.Drawing.Point(120, 19);
            this.txtValorInicial.Name = "txtValorInicial";
            this.txtValorInicial.Size = new System.Drawing.Size(379, 20);
            this.txtValorInicial.TabIndex = 1;
            //
            // btnValorInicial
            //
            this.btnValorInicial.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btnValorInicial.Location = new System.Drawing.Point(249, 53);
            this.btnValorInicial.Name = "btnValorInicial";
            this.btnValorInicial.Size = new System.Drawing.Size(250, 32);
            this.btnValorInicial.TabIndex = 2;
            this.btnValorInicial.Text = "Com valor inicial";
            this.btnValorInicial.UseVisualStyleBackColor = true;
            this.btnValorInicial.Click += new System.EventHandler(this.btnValorInicial_Click);
            //
            // frmMain
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(535, 340);
            this.Controls.Add(this.groupBox3);
            this.Controls.Add(this.groupBox2);
            this.Controls.Add(this.groupBox1);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.Name = "frmMain";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "InputBox em C#";
            this.groupBox1.ResumeLayout(false);
            this.groupBox1.PerformLayout();
            this.groupBox2.ResumeLayout(false);
            this.groupBox2.PerformLayout();
            this.groupBox3.ResumeLayout(false);
            this.groupBox3.PerformLayout();
            this.ResumeLayout(false);
        }
        #endregion
        private System.Windows.Forms.Button btnComHandler;
        private System.Windows.Forms.Label lblTeclaPressionada;
        private System.Windows.Forms.TextBox txtTeclaPressionada;
        private System.Windows.Forms.Button btnApenasTestar;
        private System.Windows.Forms.GroupBox groupBox1;
        private System.Windows.Forms.GroupBox groupBox2;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.TextBox txtApenasTestar;
        private System.Windows.Forms.GroupBox groupBox3;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.TextBox txtValorInicial;
        private System.Windows.Forms.Button btnValorInicial;
        #endregion
    }
}

Para os mais preguiçosos, faça o download do exemplo completo abaixo:
InputBox em C# (146)

É isso ai pessoal 🙂
Até o próximo
 ♦ Marcelo

Compartilhe!

About Marcelo

Nascido em Juruaia/MG em uma fazenda de criação de búfalos, e residindo na região Sul do Brasil. Trabalha com desenvolvimento de aplicações desde os 17 anos. Atualmente é Arquiteto Organizacional na Unimake Software. Para saber mais ... http://desenvolvedores.net/marcelo []'s

Deixe uma resposta

O seu endereço de e-mail não será publicado.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>