7/01/2008

TextBox só de Inteiros no .NET CF

Olá desenvolvedores .NET

Se você quer um TextBox só de inteiros e com CharacterCasing (que não há no .NET CF) apenas crie esta classe no seu projeto e arraste-o para o formulário.

Segue a classe. Existem mais 2 proprieades no componente:

OnlyNumbers
UpperCasing

Sete-os ao seu gosto e bom trabalho.

--
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Runtime.InteropServices;

namespace DeviceApplication3
{
public class TextBoxEx : TextBox
{
bool upper;
bool only_numbers;


private const int GWL_STYLE = (-16);
private const int IM_UPPERCASE = 0x0008;
private const int IM_LOWERCASE = 0x0010;
private const int IM_NUMBER = 0x2000;
IntPtr hwnd;

public bool OnlyNumbers
{
get { return only_numbers; }
set { only_numbers = value; }
}
OnlyNumbers
public bool UpperCasing
{
get { return upper; }
set { upper = value; }
}

public void setarInteiros(){
}
public void validarCaracIntRegex(KeyPressEventArgs e)
{


}

[DllImport("coredll.dll")]
private extern static int SetWindowLong(IntPtr Hwnd, int Index, int NewIndex);

[DllImport("coredll.dll")]
private extern static int GetWindowLong(IntPtr Hwnd, int Index);

[DllImport("coredll.dll")]
private extern static IntPtr GetCapture();

protected override void OnKeyPress(KeyPressEventArgs e)
{
if (OnlyNumbers) // Só numeros
{
this.Capture = true;

hwnd = GetCapture();

this.Capture = false;


int previousStyle = GetWindowLong(hwnd, GWL_STYLE);

SetWindowLong(hwnd, GWL_STYLE, previousStyle | IM_NUMBER);
}
else // Só maiúsculas
{
if (UpperCasing)
{

if (Char.IsLetter(e.KeyChar))
{

// save the current caret position

int pos = this.SelectionStart;

// insert the upper case character



this.Text = this.Text.Insert(this.SelectionStart,

Char.ToUpper(e.KeyChar).ToString());



// and update the current caret position

this.SelectionStart = pos + 1;

e.Handled = true;

}



base.OnKeyPress(e);
}
}
}
}
}