|
|
|
สอบถามหน่อยครับ ต้องการให้ texbox กรอกหรือรับค่าแต่รูปแบบเวลาอย่างเดียวครับ |
|
|
|
|
|
|
|
ลองดูตาม link นี้ครับ
http://www.visual-basic-tutorials.com/Tutorials/Controls/MaskedTextBox.html
|
|
|
|
|
Date :
2018-07-10 10:43:56 |
By :
adminliver |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
ตอบความคิดเห็นที่ : 2 เขียนโดย : ชรินทร์ เมื่อวันที่ 2018-07-10 11:21:03
รายละเอียดของการตอบ ::
จริงๆ MaskedTextBox มันก็คือ texbox นั่นแหละ อยากรู้ว่า texbox มันเขียนยังไง ก็ลองแกะ MaskedTextBox จาก .Net ดู
ใหม่ๆนี่แหละครับ เหมาะแก่การแกะโค้ดเลย เราจะได้รู้เชิงลึกของที่มาที่ไป ของ method event property ต่างๆ ของ control ที่เราใช้งานมันอยู่
Code (C#)
namespace System.Windows.Forms
{
using System;
using System.Text;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Globalization;
using System.Security;
using System.Security.Permissions;
using System.Diagnostics;
using System.Collections;
using System.Collections.Specialized;
using System.Drawing;
using System.Drawing.Design;
using System.Windows.Forms.Layout;
using System.Windows.Forms.VisualStyles;
[
ComVisible(true),
ClassInterface(ClassInterfaceType.AutoDispatch),
DefaultEvent("MaskInputRejected"),
DefaultBindingProperty("Text"),
DefaultProperty("Mask"),
Designer("System.Windows.Forms.Design.MaskedTextBoxDesigner, " + AssemblyRef.SystemDesign),
SRDescription(SR.DescriptionMaskedTextBox)
]
public class MaskedTextBox : TextBoxBase
{
private const bool forward = true;
private const bool backward = false;
private const string nullMask = "<>";
private static readonly object EVENT_MASKINPUTREJECTED = new object();
private static readonly object EVENT_VALIDATIONCOMPLETED = new object();
private static readonly object EVENT_TEXTALIGNCHANGED = new object();
private static readonly object EVENT_ISOVERWRITEMODECHANGED = new object();
private static readonly object EVENT_MASKCHANGED = new object();
private static char systemPwdChar;
private const byte imeConvertionNone = 0;
private const byte imeConvertionUpdate = 1;
private const byte imeConvertionCompleted = 2;
private int lastSelLength;
private int caretTestPos;
private static int IME_ENDING_COMPOSITION = BitVector32.CreateMask();
private static int IME_COMPLETING = BitVector32.CreateMask(IME_ENDING_COMPOSITION);
private static int HANDLE_KEY_PRESS = BitVector32.CreateMask(IME_COMPLETING);
private static int IS_NULL_MASK = BitVector32.CreateMask(HANDLE_KEY_PRESS);
private static int QUERY_BASE_TEXT = BitVector32.CreateMask(IS_NULL_MASK);
private static int REJECT_INPUT_ON_FIRST_FAILURE = BitVector32.CreateMask( QUERY_BASE_TEXT );
private static int HIDE_PROMPT_ON_LEAVE = BitVector32.CreateMask(REJECT_INPUT_ON_FIRST_FAILURE);
private static int BEEP_ON_ERROR = BitVector32.CreateMask(HIDE_PROMPT_ON_LEAVE);
private static int USE_SYSTEM_PASSWORD_CHAR = BitVector32.CreateMask(BEEP_ON_ERROR);
private static int INSERT_TOGGLED = BitVector32.CreateMask(USE_SYSTEM_PASSWORD_CHAR);
private static int CUTCOPYINCLUDEPROMPT = BitVector32.CreateMask(INSERT_TOGGLED);
private static int CUTCOPYINCLUDELITERALS = BitVector32.CreateMask(CUTCOPYINCLUDEPROMPT);
private char passwordChar;
private Type validatingType;
private IFormatProvider formatProvider;
private MaskedTextProvider maskedTextProvider;
private InsertKeyMode insertMode;
private HorizontalAlignment textAlign;
private BitVector32 flagState;
public MaskedTextBox()
{
MaskedTextProvider maskedTextProvider = new MaskedTextProvider(nullMask, CultureInfo.CurrentCulture);
this.flagState[IS_NULL_MASK] = true;
Initialize(maskedTextProvider);
}
public MaskedTextBox(string mask)
{
if (mask == null)
{
throw new ArgumentNullException();
}
MaskedTextProvider maskedTextProvider = new MaskedTextProvider(mask, CultureInfo.CurrentCulture);
this.flagState[IS_NULL_MASK] = false;
Initialize(maskedTextProvider);
}
public MaskedTextBox(MaskedTextProvider maskedTextProvider)
{
if (maskedTextProvider == null)
{
throw new ArgumentNullException();
}
this.flagState[IS_NULL_MASK] = false;
Initialize(maskedTextProvider);
}
private void Initialize(MaskedTextProvider maskedTextProvider)
{
Debug.Assert(maskedTextProvider != null, "Initializing from a null MaskProvider ref.");
this.maskedTextProvider = maskedTextProvider;
if (!this.flagState[IS_NULL_MASK])
{
SetWindowText();
}
this.passwordChar = this.maskedTextProvider.PasswordChar;
this.insertMode = InsertKeyMode.Default;
this.flagState[HIDE_PROMPT_ON_LEAVE ] = false;
this.flagState[BEEP_ON_ERROR ] = false;
this.flagState[USE_SYSTEM_PASSWORD_CHAR ] = false;
this.flagState[REJECT_INPUT_ON_FIRST_FAILURE] = false;
this.flagState[CUTCOPYINCLUDEPROMPT ] = this.maskedTextProvider.IncludePrompt;
this.flagState[CUTCOPYINCLUDELITERALS ] = this.maskedTextProvider.IncludeLiterals;
this.flagState[HANDLE_KEY_PRESS] = true;
this.caretTestPos = 0;
}
[
Browsable(false),
EditorBrowsable(EditorBrowsableState.Never),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public new bool AcceptsTab
{
get { return false; }
set {}
}
[
SRCategory(SR.CatBehavior),
SRDescription(SR.MaskedTextBoxAllowPromptAsInputDescr),
DefaultValue(true)
]
public bool AllowPromptAsInput
{
get
{
return this.maskedTextProvider.AllowPromptAsInput;
}
set
{
if( value != this.maskedTextProvider.AllowPromptAsInput )
{
MaskedTextProvider newProvider = new MaskedTextProvider(
this.maskedTextProvider.Mask,
this.maskedTextProvider.Culture,
value,
this.maskedTextProvider.PromptChar,
this.maskedTextProvider.PasswordChar,
this.maskedTextProvider.AsciiOnly );
SetMaskedTextProvider( newProvider );
}
}
}
[
Browsable(false),
EditorBrowsable(EditorBrowsableState.Never),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public new event EventHandler AcceptsTabChanged
{
add { }
remove { }
}
[
SRCategory(SR.CatBehavior),
SRDescription(SR.MaskedTextBoxAsciiOnlyDescr),
RefreshProperties(RefreshProperties.Repaint),
DefaultValue(false)
]
public bool AsciiOnly
{
get
{
return this.maskedTextProvider.AsciiOnly;
}
set
{
if( value != this.maskedTextProvider.AsciiOnly )
{
MaskedTextProvider newProvider = new MaskedTextProvider(
this.maskedTextProvider.Mask,
this.maskedTextProvider.Culture,
this.maskedTextProvider.AllowPromptAsInput,
this.maskedTextProvider.PromptChar,
this.maskedTextProvider.PasswordChar,
value );
SetMaskedTextProvider( newProvider );
}
}
}
[
SRCategory(SR.CatBehavior),
SRDescription(SR.MaskedTextBoxBeepOnErrorDescr),
DefaultValue(false)
]
public bool BeepOnError
{
get
{
return this.flagState[BEEP_ON_ERROR];
}
set
{
this.flagState[BEEP_ON_ERROR] = value;
}
}
[
Browsable(false),
EditorBrowsable(EditorBrowsableState.Never),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public new bool CanUndo
{
get
{
return false;
}
}
protected override CreateParams CreateParams
{
[SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)]
get
{
CreateParams cp = base.CreateParams;
HorizontalAlignment align = RtlTranslateHorizontal(textAlign);
cp.ExStyle &= ~NativeMethods.WS_EX_RIGHT;
switch (align)
{
case HorizontalAlignment.Left:
cp.Style |= NativeMethods.ES_LEFT;
break;
case HorizontalAlignment.Center:
cp.Style |= NativeMethods.ES_CENTER;
break;
case HorizontalAlignment.Right:
cp.Style |= NativeMethods.ES_RIGHT;
break;
}
return cp;
}
}
[
SRCategory(SR.CatBehavior),
SRDescription(SR.MaskedTextBoxCultureDescr),
RefreshProperties(RefreshProperties.Repaint),
]
public CultureInfo Culture
{
get
{
return this.maskedTextProvider.Culture;
}
set
{
if( value == null )
{
throw new ArgumentNullException();
}
if( !this.maskedTextProvider.Culture.Equals(value) )
{
MaskedTextProvider newProvider = new MaskedTextProvider(
this.maskedTextProvider.Mask,
value,
this.maskedTextProvider.AllowPromptAsInput,
this.maskedTextProvider.PromptChar,
this.maskedTextProvider.PasswordChar,
this.maskedTextProvider.AsciiOnly );
SetMaskedTextProvider( newProvider );
}
}
}
[
SRCategory(SR.CatBehavior),
SRDescription(SR.MaskedTextBoxCutCopyMaskFormat),
RefreshProperties(RefreshProperties.Repaint),
DefaultValue(MaskFormat.IncludeLiterals)
]
public MaskFormat CutCopyMaskFormat
{
get
{
if( this.flagState[CUTCOPYINCLUDEPROMPT] )
{
if( this.flagState[CUTCOPYINCLUDELITERALS] )
{
return MaskFormat.IncludePromptAndLiterals;
}
return MaskFormat.IncludePrompt;
}
if( this.flagState[CUTCOPYINCLUDELITERALS] )
{
return MaskFormat.IncludeLiterals;
}
return MaskFormat.ExcludePromptAndLiterals;
}
set
{
if (!ClientUtils.IsEnumValid(value, (int)value, (int)MaskFormat.ExcludePromptAndLiterals, (int)MaskFormat.IncludePromptAndLiterals))
{
throw new InvalidEnumArgumentException("value", (int)value, typeof(MaskFormat));
}
if( value == MaskFormat.IncludePrompt )
{
this.flagState[CUTCOPYINCLUDEPROMPT] = true;
this.flagState[CUTCOPYINCLUDELITERALS] = false;
}
else if( value == MaskFormat.IncludeLiterals )
{
this.flagState[CUTCOPYINCLUDEPROMPT] = false;
this.flagState[CUTCOPYINCLUDELITERALS] = true;
}
else
{
bool include = value == MaskFormat.IncludePromptAndLiterals;
this.flagState[CUTCOPYINCLUDEPROMPT] = include;
this.flagState[CUTCOPYINCLUDELITERALS] = include;
}
}
}
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public IFormatProvider FormatProvider
{
get
{
return this.formatProvider;
}
set
{
this.formatProvider = value;
}
}
[
SRCategory(SR.CatBehavior),
SRDescription(SR.MaskedTextBoxHidePromptOnLeaveDescr),
RefreshProperties(RefreshProperties.Repaint),
DefaultValue(false)
]
public bool HidePromptOnLeave
{
get
{
return this.flagState[HIDE_PROMPT_ON_LEAVE];
}
set
{
if( this.flagState[HIDE_PROMPT_ON_LEAVE] != value )
{
this.flagState[HIDE_PROMPT_ON_LEAVE] = value;
if( !this.flagState[IS_NULL_MASK]&& !this.Focused && !this.MaskFull && !this.DesignMode )
{
SetWindowText();
}
}
}
}
private bool IncludeLiterals
{
get
{
return this.maskedTextProvider.IncludeLiterals;
}
set
{
this.maskedTextProvider.IncludeLiterals = value;
}
}
private bool IncludePrompt
{
get
{
return this.maskedTextProvider.IncludePrompt;
}
set
{
this.maskedTextProvider.IncludePrompt = value;
}
}
[
SRCategory(SR.CatBehavior),
SRDescription(SR.MaskedTextBoxInsertKeyModeDescr),
DefaultValue(InsertKeyMode.Default)
]
public InsertKeyMode InsertKeyMode
{
get
{
return this.insertMode;
}
set
{
if (!ClientUtils.IsEnumValid(value, (int)value, (int)InsertKeyMode.Default, (int)InsertKeyMode.Overwrite))
{
throw new InvalidEnumArgumentException("value", (int)value, typeof(InsertKeyMode));
}
if (this.insertMode != value)
{
bool isOverwrite = this.IsOverwriteMode;
this.insertMode = value;
if (isOverwrite != this.IsOverwriteMode)
{
OnIsOverwriteModeChanged(EventArgs.Empty);
}
}
}
}
protected override bool IsInputKey(Keys keyData)
{
if ((keyData & Keys.KeyCode) == Keys.Return)
{
return false;
}
return base.IsInputKey(keyData);
}
[
Browsable(false)
]
public bool IsOverwriteMode
{
get
{
if( this.flagState[IS_NULL_MASK])
{
return false;
}
switch (this.insertMode)
{
case InsertKeyMode.Overwrite:
return true;
case InsertKeyMode.Insert:
return false;
case InsertKeyMode.Default:
return this.flagState[INSERT_TOGGLED];
default:
Debug.Fail("Invalid InsertKeyMode. This code path should have never been executed.");
return false;
}
}
}
[
SRCategory(SR.CatPropertyChanged),
SRDescription(SR.MaskedTextBoxIsOverwriteModeChangedDescr)
]
public event EventHandler IsOverwriteModeChanged
{
add
{
Events.AddHandler(EVENT_ISOVERWRITEMODECHANGED, value);
}
remove
{
Events.RemoveHandler(EVENT_ISOVERWRITEMODECHANGED, value);
}
}
[
Browsable(false),
EditorBrowsable(EditorBrowsableState.Never),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public new string[] Lines
{
get
{
string[] lines;
this.flagState[QUERY_BASE_TEXT] = true;
try
{
lines = base.Lines;
}
finally
{
this.flagState[QUERY_BASE_TEXT] = false;
}
return lines;
}
set {}
}
[
SRCategory(SR.CatBehavior),
SRDescription(SR.MaskedTextBoxMaskDescr),
RefreshProperties(RefreshProperties.Repaint),
DefaultValue(""),
MergableProperty(false),
Localizable(true),
Editor("System.Windows.Forms.Design.MaskPropertyEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor))
]
public string Mask
{
get
{
return this.flagState[IS_NULL_MASK]? string.Empty : this.maskedTextProvider.Mask;
}
set
{
if( this.flagState[IS_NULL_MASK] == string.IsNullOrEmpty( value ) && (this.flagState[IS_NULL_MASK] || value == this.maskedTextProvider.Mask) )
{
return;
}
string text = null;
string newMask = value;
if( string.IsNullOrEmpty( value ) )
{
string formattedText = TextOutput;
string unformattedText = this.maskedTextProvider.ToString(false, false);
this.flagState[IS_NULL_MASK] = true;
if( this.maskedTextProvider.IsPassword )
{
SetEditControlPasswordChar(this.maskedTextProvider.PasswordChar);
}
SetWindowText(unformattedText, false, false );
EventArgs e = EventArgs.Empty;
OnMaskChanged(e);
if( unformattedText != formattedText )
{
OnTextChanged(e);
}
newMask = nullMask;
}
else
{
foreach( char c in value )
{
if( !MaskedTextProvider.IsValidMaskChar( c ) )
{
throw new ArgumentException( SR.GetString( SR.MaskedTextBoxMaskInvalidChar) );
}
}
if( this.flagState[IS_NULL_MASK] )
{
text = this.Text;
}
}
MaskedTextProvider newProvider = new MaskedTextProvider(
newMask,
this.maskedTextProvider.Culture,
this.maskedTextProvider.AllowPromptAsInput,
this.maskedTextProvider.PromptChar,
this.maskedTextProvider.PasswordChar,
this.maskedTextProvider.AsciiOnly );
SetMaskedTextProvider( newProvider, text );
}
}
[
SRCategory(SR.CatPropertyChanged),
SRDescription(SR.MaskedTextBoxMaskChangedDescr)
]
public event EventHandler MaskChanged
{
add
{
Events.AddHandler(EVENT_MASKCHANGED, value);
}
remove
{
Events.RemoveHandler(EVENT_MASKCHANGED, value);
}
}
[
Browsable(false)
]
public bool MaskCompleted
{
get
{
return this.maskedTextProvider.MaskCompleted;
}
}
[
Browsable(false)
]
public bool MaskFull
{
get
{
return this.maskedTextProvider.MaskFull;
}
}
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public MaskedTextProvider MaskedTextProvider
{
get
{
return this.flagState[IS_NULL_MASK] ? null : (MaskedTextProvider) this.maskedTextProvider.Clone();
}
}
[
SRCategory(SR.CatBehavior),
SRDescription(SR.MaskedTextBoxMaskInputRejectedDescr)
]
public event MaskInputRejectedEventHandler MaskInputRejected
{
add
{
Events.AddHandler(EVENT_MASKINPUTREJECTED, value);
}
remove
{
Events.RemoveHandler(EVENT_MASKINPUTREJECTED, value);
}
}
[
Browsable(false),
EditorBrowsable(EditorBrowsableState.Never),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public override int MaxLength
{
get{ return base.MaxLength; }
set{}
}
[
Browsable(false),
EditorBrowsable(EditorBrowsableState.Never),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public override bool Multiline
{
get { return false; }
set {}
}
[
Browsable(false),
EditorBrowsable(EditorBrowsableState.Never),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public new event EventHandler MultilineChanged
{
add { }
remove { }
}
[
SRCategory(SR.CatBehavior),
SRDescription(SR.MaskedTextBoxPasswordCharDescr),
RefreshProperties(RefreshProperties.Repaint),
DefaultValue('\0')
]
public char PasswordChar
{
get
{
return this.maskedTextProvider.PasswordChar;
}
set
{
if( !MaskedTextProvider.IsValidPasswordChar(value) )
{
throw new ArgumentException(SR.GetString(SR.MaskedTextBoxInvalidCharError) );
}
if( this.passwordChar != value )
{
if( value == this.maskedTextProvider.PromptChar )
{
throw new InvalidOperationException( SR.GetString(SR.MaskedTextBoxPasswordAndPromptCharError) );
}
this.passwordChar = value;
if (!this.UseSystemPasswordChar)
{
this.maskedTextProvider.PasswordChar = value;
if( this.flagState[IS_NULL_MASK])
{
SetEditControlPasswordChar(value);
}
else
{
SetWindowText();
}
VerifyImeRestrictedModeChanged();
}
}
}
}
internal override bool PasswordProtect
{
get
{
if( this.maskedTextProvider != null )
{
return this.maskedTextProvider.IsPassword;
}
return base.PasswordProtect;
}
}
[
SRCategory(SR.CatAppearance),
SRDescription(SR.MaskedTextBoxPromptCharDescr),
RefreshProperties(RefreshProperties.Repaint),
Localizable(true),
DefaultValue('_')
]
public char PromptChar
{
get
{
return this.maskedTextProvider.PromptChar;
}
set
{
if( !MaskedTextProvider.IsValidInputChar(value) )
{
throw new ArgumentException(SR.GetString(SR.MaskedTextBoxInvalidCharError) );
}
if( this.maskedTextProvider.PromptChar != value )
{
if( value == this.passwordChar || value == this.maskedTextProvider.PasswordChar )
{
throw new InvalidOperationException( SR.GetString(SR.MaskedTextBoxPasswordAndPromptCharError) );
}
MaskedTextProvider newProvider = new MaskedTextProvider(
this.maskedTextProvider.Mask,
this.maskedTextProvider.Culture,
this.maskedTextProvider.AllowPromptAsInput,
value,
this.maskedTextProvider.PasswordChar,
this.maskedTextProvider.AsciiOnly );
SetMaskedTextProvider( newProvider );
}
}
}
public new bool ReadOnly
{
get
{
return base.ReadOnly;
}
set
{
if (this.ReadOnly != value)
{
base.ReadOnly = value;
if (!this.flagState[IS_NULL_MASK])
{
SetWindowText();
}
}
}
}
[
SRCategory(SR.CatBehavior),
SRDescription(SR.MaskedTextBoxRejectInputOnFirstFailureDescr),
DefaultValue(false)
]
public bool RejectInputOnFirstFailure
{
get
{
return this.flagState[REJECT_INPUT_ON_FIRST_FAILURE];
}
set
{
this.flagState[REJECT_INPUT_ON_FIRST_FAILURE] = value;
}
}
/* No longer needed since Culture has been removed from the property browser - Left here for documentation.
[EditorBrowsable(EditorBrowsableState.Never)]
private void ResetCulture()
{
this.Culture = CultureInfo.CurrentCulture;
}*/
[
SRCategory(SR.CatBehavior),
SRDescription(SR.MaskedTextBoxResetOnPrompt),
DefaultValue(true)
]
public bool ResetOnPrompt
{
get
{
return this.maskedTextProvider.ResetOnPrompt;
}
set
{
this.maskedTextProvider.ResetOnPrompt = value;
}
}
[
SRCategory(SR.CatBehavior),
SRDescription(SR.MaskedTextBoxResetOnSpace),
DefaultValue(true)
]
public bool ResetOnSpace
{
get
{
return this.maskedTextProvider.ResetOnSpace;
}
set
{
this.maskedTextProvider.ResetOnSpace = value;
}
}
[
SRCategory(SR.CatBehavior),
SRDescription(SR.MaskedTextBoxSkipLiterals),
DefaultValue(true)
]
public bool SkipLiterals
{
get
{
return this.maskedTextProvider.SkipLiterals;
}
set
{
this.maskedTextProvider.SkipLiterals = value;
}
}
public override string SelectedText
{
get
{
if( this.flagState[IS_NULL_MASK])
{
return base.SelectedText;
}
return GetSelectedText();
}
set
{
SetSelectedTextInternal(value, true);
}
}
internal override void SetSelectedTextInternal(string value, bool clearUndo)
{
if (this.flagState[IS_NULL_MASK])
{
base.SetSelectedTextInternal(value, true);
return;
}
PasteInt( value );
}
private void ImeComplete()
{
this.flagState[IME_COMPLETING] = true;
ImeNotify(NativeMethods.CPS_COMPLETE);
}
private void ImeNotify(int action)
{
HandleRef handle = new HandleRef(this, this.Handle);
IntPtr inputContext = UnsafeNativeMethods.ImmGetContext(handle);
if (inputContext != IntPtr.Zero)
{
try
{
UnsafeNativeMethods.ImmNotifyIME(new HandleRef(null, inputContext), NativeMethods.NI_COMPOSITIONSTR, action, 0);
}
finally
{
UnsafeNativeMethods.ImmReleaseContext(handle, new HandleRef(null, inputContext));
}
}
else
{
Debug.Fail("Could not get IME input context.");
}
}
private void SetEditControlPasswordChar( char pwdChar )
{
if (this.IsHandleCreated)
{
SendMessage(NativeMethods.EM_SETPASSWORDCHAR, pwdChar, 0);
Invalidate();
}
}
private char SystemPasswordChar
{
get
{
if (MaskedTextBox.systemPwdChar == '\0')
{
/*
StringBuilder charVal = new StringBuilder(20);
bool foundRsc = false;
int IDS_PASSWORDCHAR = 0x1076;
IntSecurity.UnmanagedCode.Assert();
try
{
IntPtr hModule = UnsafeNativeMethods.GetModuleHandle("comctl32.dll");
Debug.Assert(hModule != IntPtr.Zero, String.Format("Could not get a handle to comctl32.dll - Error: 0x{0:X8}", Marshal.GetLastWin32Error()));
foundRsc = UnsafeNativeMethods.LoadString(new HandleRef(null, hModule), IDS_PASSWORDCHAR, charVal, charVal.Capacity);
}
catch( Exception ex )
{
if( ClientUtils.IsSecurityOrCriticalException( ex ) )
{
throw;
}
}
finally
{
CodeAccessPermission.RevertAssert();
}
MaskedTextBox.systemPwdChar = foundRsc ? (char) int.Parse(charVal.ToString()) : MaskedTextProvider.DefaultPasswordChar;
*/
TextBox txtBox = new TextBox();
txtBox.UseSystemPasswordChar = true;
MaskedTextBox.systemPwdChar = txtBox.PasswordChar;
txtBox.Dispose();
}
return MaskedTextBox.systemPwdChar;
}
}
[
Editor("System.Windows.Forms.Design.MaskedTextBoxTextEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)),
SRCategory(SR.CatAppearance),
RefreshProperties(RefreshProperties.Repaint),
Bindable(true),
DefaultValue(""),
Localizable(true)
]
public override string Text
{
get
{
if( this.flagState[IS_NULL_MASK] || this.flagState[QUERY_BASE_TEXT])
{
return base.Text;
}
return TextOutput;
}
set
{
if (this.flagState[IS_NULL_MASK])
{
base.Text = value;
return;
}
if (string.IsNullOrEmpty(value))
{
Delete(Keys.Delete, 0, this.maskedTextProvider.Length);
}
else
{
if( this.RejectInputOnFirstFailure )
{
MaskedTextResultHint hint;
string oldText = TextOutput;
if (this.maskedTextProvider.Set(value, out this.caretTestPos, out hint))
{
if( TextOutput != oldText )
{
SetText();
}
this.SelectionStart = ++this.caretTestPos;
}
else
{
OnMaskInputRejected(new MaskInputRejectedEventArgs(this.caretTestPos, hint));
}
}
else
{
Replace(value, /*startPosition*/ 0, /*selectionLen*/ this.maskedTextProvider.Length);
}
}
}
}
[Browsable( false )]
public override int TextLength
{
get
{
if( this.flagState[IS_NULL_MASK] )
{
return base.TextLength;
}
return GetFormattedDisplayString().Length;
}
}
private string TextOutput
{
get
{
Debug.Assert( !this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided." );
return this.maskedTextProvider.ToString();
}
}
[
Localizable(true),
SRCategory(SR.CatAppearance),
DefaultValue(HorizontalAlignment.Left),
SRDescription(SR.TextBoxTextAlignDescr)
]
public HorizontalAlignment TextAlign
{
get
{
return textAlign;
}
set
{
if (textAlign != value)
{
if (!ClientUtils.IsEnumValid(value, (int)value, (int)HorizontalAlignment.Left, (int)HorizontalAlignment.Center))
{
throw new InvalidEnumArgumentException("value", (int)value, typeof(HorizontalAlignment));
}
textAlign = value;
RecreateHandle();
OnTextAlignChanged(EventArgs.Empty);
}
}
}
[
SRCategory(SR.CatPropertyChanged),
SRDescription(SR.RadioButtonOnTextAlignChangedDescr)
]
public event EventHandler TextAlignChanged
{
add
{
Events.AddHandler(EVENT_TEXTALIGNCHANGED, value);
}
remove
{
Events.RemoveHandler(EVENT_TEXTALIGNCHANGED, value);
}
}
[
SRCategory(SR.CatBehavior),
SRDescription(SR.MaskedTextBoxTextMaskFormat),
RefreshProperties(RefreshProperties.Repaint),
DefaultValue(MaskFormat.IncludeLiterals)
]
public MaskFormat TextMaskFormat
{
get
{
if( this.IncludePrompt )
{
if( this.IncludeLiterals )
{
return MaskFormat.IncludePromptAndLiterals;
}
return MaskFormat.IncludePrompt;
}
if( this.IncludeLiterals )
{
return MaskFormat.IncludeLiterals;
}
return MaskFormat.ExcludePromptAndLiterals;
}
set
{
if( this.TextMaskFormat == value )
{
return;
}
if (!ClientUtils.IsEnumValid(value, (int)value, (int)MaskFormat.ExcludePromptAndLiterals, (int)MaskFormat.IncludePromptAndLiterals))
{
throw new InvalidEnumArgumentException("value", (int)value, typeof(MaskFormat));
}
string oldText = this.flagState[IS_NULL_MASK] ? null : TextOutput;
if( value == MaskFormat.IncludePrompt )
{
this.IncludePrompt = true;
this.IncludeLiterals = false;
}
else if( value == MaskFormat.IncludeLiterals )
{
this.IncludePrompt = false;
this.IncludeLiterals = true;
}
else
{
bool include = value == MaskFormat.IncludePromptAndLiterals;
this.IncludePrompt = include;
this.IncludeLiterals = include;
}
if( oldText != null && oldText != TextOutput )
{
OnTextChanged(EventArgs.Empty);
}
}
}
public override string ToString()
{
if( this.flagState[IS_NULL_MASK] )
{
return base.ToString();
}
bool includePrompt = this.IncludePrompt;
bool includeLits = this.IncludeLiterals;
string str;
try
{
this.IncludePrompt = this.IncludeLiterals = true;
str = base.ToString();
}
finally
{
this.IncludePrompt = includePrompt;
this.IncludeLiterals = includeLits;
}
return str;
}
[
SRCategory(SR.CatFocus),
SRDescription(SR.MaskedTextBoxTypeValidationCompletedDescr)
]
public event TypeValidationEventHandler TypeValidationCompleted
{
add
{
Events.AddHandler(EVENT_VALIDATIONCOMPLETED, value);
}
remove
{
Events.RemoveHandler(EVENT_VALIDATIONCOMPLETED, value);
}
}
[
SRCategory(SR.CatBehavior),
SRDescription(SR.MaskedTextBoxUseSystemPasswordCharDescr),
RefreshProperties(RefreshProperties.Repaint),
DefaultValue(false)
]
public bool UseSystemPasswordChar
{
get
{
return this.flagState[USE_SYSTEM_PASSWORD_CHAR];
}
set
{
if (value != this.flagState[USE_SYSTEM_PASSWORD_CHAR])
{
if (value)
{
if( this.SystemPasswordChar == this.PromptChar )
{
throw new InvalidOperationException( SR.GetString(SR.MaskedTextBoxPasswordAndPromptCharError) );
}
this.maskedTextProvider.PasswordChar = this.SystemPasswordChar;
}
else
{
this.maskedTextProvider.PasswordChar = this.passwordChar;
}
this.flagState[USE_SYSTEM_PASSWORD_CHAR] = value;
if( this.flagState[IS_NULL_MASK])
{
SetEditControlPasswordChar(this.maskedTextProvider.PasswordChar);
}
else
{
SetWindowText();
}
VerifyImeRestrictedModeChanged();
}
}
}
[
Browsable(false),
DefaultValue(null)
]
public Type ValidatingType
{
get
{
return this.validatingType;
}
set
{
if( this.validatingType != value )
{
this.validatingType = value;
}
}
}
[
Browsable(false),
EditorBrowsable(EditorBrowsableState.Never),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public new bool WordWrap
{
get { return false; }
set {}
}
[
EditorBrowsable(EditorBrowsableState.Never)
]
public new void ClearUndo()
{
}
[
EditorBrowsable(EditorBrowsableState.Advanced),
UIPermission(SecurityAction.InheritanceDemand, Window = UIPermissionWindow.AllWindows)
]
protected override void CreateHandle()
{
if (!this.flagState[IS_NULL_MASK] && RecreatingHandle)
{
SetWindowText(GetFormattedDisplayString(), false, false);
}
base.CreateHandle();
}
private void Delete(Keys keyCode, int startPosition, int selectionLen)
{
Debug.Assert( !this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided." );
Debug.Assert( keyCode == Keys.Delete || keyCode == Keys.Back, "Delete called with keyCode == " + keyCode.ToString() );
Debug.Assert( startPosition >= 0 && ((startPosition + selectionLen) <= this.maskedTextProvider.Length), "Invalid position range." );
this.caretTestPos = startPosition;
if( selectionLen == 0 )
{
if( keyCode == Keys.Back )
{
if( startPosition == 0 )
{
return;
}
startPosition--;
}
else
{
if( (startPosition + selectionLen) == this.maskedTextProvider.Length )
{
return;
}
}
}
int tempPos;
int endPos = selectionLen > 0 ? startPosition + selectionLen - 1 : startPosition;
MaskedTextResultHint hint;
string oldText = TextOutput;
if (this.maskedTextProvider.RemoveAt(startPosition, endPos, out tempPos, out hint))
{
if( TextOutput != oldText )
{
SetText();
this.caretTestPos = startPosition;
}
else
{
if( selectionLen > 0 )
{
this.caretTestPos = startPosition;
}
else
{
if( hint == MaskedTextResultHint.NoEffect )
{
if( keyCode == Keys.Delete )
{
this.caretTestPos = this.maskedTextProvider.FindEditPositionFrom(startPosition, forward);
}
else
{
if( this.maskedTextProvider.FindAssignedEditPositionFrom( startPosition, forward ) == MaskedTextProvider.InvalidIndex )
{
this.caretTestPos = this.maskedTextProvider.FindAssignedEditPositionFrom(startPosition, backward);
}
else
{
this.caretTestPos = this.maskedTextProvider.FindEditPositionFrom(startPosition, backward);
}
if( this.caretTestPos != MaskedTextProvider.InvalidIndex )
{
this.caretTestPos++;
}
}
if( this.caretTestPos == MaskedTextProvider.InvalidIndex )
{
this.caretTestPos = startPosition;
}
}
else
{
if( keyCode == Keys.Back )
{
this.caretTestPos = startPosition;
}
}
}
}
}
else
{
OnMaskInputRejected(new MaskInputRejectedEventArgs(tempPos, hint));
}
base.SelectInternal( this.caretTestPos, 0, this.maskedTextProvider.Length );
return;
}
public override char GetCharFromPosition(Point pt)
{
char ch;
this.flagState[QUERY_BASE_TEXT] = true;
try
{
ch = base.GetCharFromPosition(pt);
}
finally
{
this.flagState[QUERY_BASE_TEXT] = false;
}
return ch;
}
public override int GetCharIndexFromPosition(Point pt)
{
int index;
this.flagState[QUERY_BASE_TEXT] = true;
try
{
index = base.GetCharIndexFromPosition(pt);
}
finally
{
this.flagState[QUERY_BASE_TEXT] = false;
}
return index;
}
internal override int GetEndPosition()
{
if( this.flagState[IS_NULL_MASK])
{
return base.GetEndPosition();
}
int pos = this.maskedTextProvider.FindEditPositionFrom( this.maskedTextProvider.LastAssignedPosition + 1, forward );
if( pos == MaskedTextProvider.InvalidIndex )
{
pos = this.maskedTextProvider.LastAssignedPosition + 1;
}
return pos;
}
[
EditorBrowsable(EditorBrowsableState.Never)
]
public new int GetFirstCharIndexOfCurrentLine()
{
return 0;
}
[
EditorBrowsable(EditorBrowsableState.Never)
]
public new int GetFirstCharIndexFromLine(int lineNumber)
{
return 0;
}
private string GetFormattedDisplayString()
{
Debug.Assert( !this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided." );
bool includePrompt;
if (this.ReadOnly)
{
includePrompt = false;
}
else if (this.DesignMode)
{
includePrompt = true;
}
else
{
includePrompt = !(this.HidePromptOnLeave && !this.Focused);
}
return this.maskedTextProvider.ToString(/*ignorePwdChar */ false, includePrompt, /*includeLiterals*/ true, 0, this.maskedTextProvider.Length);
}
[
EditorBrowsable(EditorBrowsableState.Never)
]
public override int GetLineFromCharIndex(int index)
{
return 0;
}
public override Point GetPositionFromCharIndex(int index)
{
Point pos;
this.flagState[QUERY_BASE_TEXT] = true;
try
{
pos = base.GetPositionFromCharIndex(index);
}
finally
{
this.flagState[QUERY_BASE_TEXT] = false;
}
return pos;
}
internal override Size GetPreferredSizeCore(Size proposedConstraints)
{
Size size;
this.flagState[QUERY_BASE_TEXT] = true;
try
{
size = base.GetPreferredSizeCore( proposedConstraints );
}
finally
{
this.flagState[QUERY_BASE_TEXT] = false;
}
return size;
}
private string GetSelectedText()
{
Debug.Assert( !this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided." );
int selStart, selLength;
base.GetSelectionStartAndLength( out selStart, out selLength );
if( selLength == 0 )
{
return string.Empty;
}
bool includePrompt = (CutCopyMaskFormat & MaskFormat.IncludePrompt ) != 0;
bool includeLiterals = (CutCopyMaskFormat & MaskFormat.IncludeLiterals) != 0;
return this.maskedTextProvider.ToString( /*ignorePasswordChar*/ true, includePrompt, includeLiterals, selStart, selLength );
}
protected override void OnBackColorChanged(EventArgs e)
{
base.OnBackColorChanged(e);
if (Application.RenderWithVisualStyles && this.IsHandleCreated && this.BorderStyle == BorderStyle.Fixed3D)
{
SafeNativeMethods.RedrawWindow(new HandleRef(this, this.Handle), null, NativeMethods.NullHandleRef, NativeMethods.RDW_INVALIDATE | NativeMethods.RDW_FRAME);
}
}
protected override void OnHandleCreated(EventArgs e)
{
base.OnHandleCreated(e);
base.SetSelectionOnHandle();
if( this.flagState[IS_NULL_MASK]&& this.maskedTextProvider.IsPassword )
{
SetEditControlPasswordChar(this.maskedTextProvider.PasswordChar);
}
}
[
EditorBrowsable(EditorBrowsableState.Advanced)
]
protected virtual void OnIsOverwriteModeChanged(EventArgs e)
{
EventHandler eh = Events[EVENT_ISOVERWRITEMODECHANGED] as EventHandler;
if (eh != null)
{
eh(this, e);
}
}
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if( this.flagState[IS_NULL_MASK])
{
return;
}
Keys keyCode = e.KeyCode;
if( keyCode == Keys.Return || keyCode == Keys.Escape )
{
this.flagState[HANDLE_KEY_PRESS] = false;
}
if (keyCode == Keys.Insert && e.Modifiers == Keys.None && this.insertMode == InsertKeyMode.Default)
{
this.flagState[INSERT_TOGGLED] = !this.flagState[INSERT_TOGGLED];
OnIsOverwriteModeChanged(EventArgs.Empty);
return;
}
if (e.Control && char.IsLetter((char)keyCode))
{
switch (keyCode)
{
case Keys.H:
keyCode = Keys.Back;
break;
default:
this.flagState[HANDLE_KEY_PRESS] = false;
return;
}
}
if ( keyCode == Keys.Delete || keyCode == Keys.Back )
{
if (!this.ReadOnly)
{
int selectionLen;
int startPosition;
base.GetSelectionStartAndLength( out startPosition, out selectionLen );
switch (e.Modifiers)
{
case Keys.Shift:
if( keyCode == Keys.Delete )
{
keyCode = Keys.Back;
}
goto default;
case Keys.Control:
if( selectionLen == 0 )
{
if( keyCode == Keys.Delete )
{
selectionLen = this.maskedTextProvider.Length - startPosition;
}
else
{
selectionLen = startPosition == this.maskedTextProvider.Length /*at end of text*/ ? startPosition : startPosition + 1;
startPosition = 0;
}
}
goto default;
default:
if( !this.flagState[HANDLE_KEY_PRESS] )
{
this.flagState[HANDLE_KEY_PRESS] = true;
}
break;
}
/* This code is no longer needed after fixing bug#517013 - Left here for reference DON'T DELETE.
if ((ImeModeConversion.InputLanguageTable == ImeModeConversion.KoreanTable) && this.flagState[IME_ENDING_COMPOSITION])
{
if(keyCode == Keys.Back && selectionLen == 0)
{
startPosition++;
}
}
*/
Delete(keyCode, startPosition, selectionLen);
e.SuppressKeyPress = true;
}
}
}
protected override void OnKeyPress(KeyPressEventArgs e)
{
base.OnKeyPress(e);
if( this.flagState[IS_NULL_MASK])
{
return;
}
if( !this.flagState[HANDLE_KEY_PRESS] )
{
this.flagState[HANDLE_KEY_PRESS] = true;
if (!char.IsLetter(e.KeyChar))
{
return;
}
}
if( !this.ReadOnly)
{
MaskedTextResultHint hint;
int selectionStart;
int selectionLen;
base.GetSelectionStartAndLength( out selectionStart, out selectionLen );
string oldText = TextOutput;
if (PlaceChar(e.KeyChar, selectionStart, selectionLen, this.IsOverwriteMode, out hint))
{
if( TextOutput != oldText )
{
SetText();
}
this.SelectionStart = ++this.caretTestPos;
if (ImeModeConversion.InputLanguageTable == ImeModeConversion.KoreanTable)
{
int editPos = this.maskedTextProvider.FindUnassignedEditPositionFrom(this.caretTestPos, forward);
if (editPos == MaskedTextProvider.InvalidIndex)
{
ImeComplete();
}
}
}
else
{
OnMaskInputRejected(new MaskInputRejectedEventArgs(this.caretTestPos, hint));
}
if( selectionLen > 0 )
{
this.SelectionLength = 0;
}
e.Handled = true;
}
}
protected override void OnKeyUp(KeyEventArgs e)
{
base.OnKeyUp(e);
if (this.flagState[IME_COMPLETING])
{
this.flagState[IME_COMPLETING] = false;
}
if( this.flagState[IME_ENDING_COMPOSITION] )
{
this.flagState[IME_ENDING_COMPOSITION] = false;
}
}
[
EditorBrowsable(EditorBrowsableState.Advanced)
]
protected virtual void OnMaskChanged(EventArgs e)
{
EventHandler eh = Events[EVENT_MASKCHANGED] as EventHandler;
if (eh != null)
{
eh(this, e);
}
}
private void OnMaskInputRejected(MaskInputRejectedEventArgs e)
{
Debug.Assert( !this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided." );
if (this.BeepOnError)
{
System.Media.SoundPlayer sp = new System.Media.SoundPlayer();
sp.Play();
}
MaskInputRejectedEventHandler eh = Events[EVENT_MASKINPUTREJECTED] as MaskInputRejectedEventHandler;
if (eh != null)
{
eh(this, e);
}
}
[
EditorBrowsable(EditorBrowsableState.Never)
]
protected override void OnMultilineChanged(EventArgs e)
{
}
protected virtual void OnTextAlignChanged(EventArgs e)
{
EventHandler eh = Events[EVENT_TEXTALIGNCHANGED] as EventHandler;
if (eh != null)
{
eh(this, e);
}
}
private void OnTypeValidationCompleted(TypeValidationEventArgs e)
{
TypeValidationEventHandler eh = Events[EVENT_VALIDATIONCOMPLETED] as TypeValidationEventHandler;
if (eh != null)
{
eh(this, e);
}
}
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected override void OnValidating(CancelEventArgs e)
{
PerformTypeValidation(e);
base.OnValidating(e);
}
protected override void OnTextChanged(EventArgs e)
{
bool queryBaseText = this.flagState[QUERY_BASE_TEXT];
this.flagState[QUERY_BASE_TEXT] = false;
try
{
base.OnTextChanged(e);
}
finally
{
this.flagState[QUERY_BASE_TEXT] = queryBaseText;
}
}
private void Replace(string text, int startPosition, int selectionLen)
{
Debug.Assert( !this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided." );
Debug.Assert(text != null, "text is null.");
MaskedTextProvider clonedProvider = (MaskedTextProvider) this.maskedTextProvider.Clone();
int currentCaretPos = this.caretTestPos;
MaskedTextResultHint hint = MaskedTextResultHint.NoEffect;
int endPos = startPosition + selectionLen - 1;
if( this.RejectInputOnFirstFailure )
{
bool succeeded;
succeeded = (startPosition > endPos) ?
clonedProvider.InsertAt(text, startPosition, out this.caretTestPos, out hint ) :
clonedProvider.Replace(text, startPosition, endPos, out this.caretTestPos, out hint);
if( !succeeded )
{
OnMaskInputRejected(new MaskInputRejectedEventArgs(this.caretTestPos, hint));
}
}
else
{
MaskedTextResultHint tempHint = hint;
int testPos;
foreach (char ch in text)
{
if( !this.maskedTextProvider.VerifyEscapeChar( ch, startPosition ))
{
testPos = clonedProvider.FindEditPositionFrom(startPosition, forward);
if( testPos == MaskedTextProvider.InvalidIndex )
{
OnMaskInputRejected(new MaskInputRejectedEventArgs(startPosition, MaskedTextResultHint.UnavailableEditPosition));
continue;
}
startPosition = testPos;
}
int length = endPos >= startPosition ? 1 : 0;
bool replace = length > 0;
if (PlaceChar(clonedProvider, ch, startPosition, length, replace, out tempHint))
{
startPosition = this.caretTestPos + 1;
if (tempHint == MaskedTextResultHint.Success && hint != tempHint)
{
hint = tempHint;
}
}
else
{
OnMaskInputRejected(new MaskInputRejectedEventArgs(startPosition, tempHint));
}
}
if (selectionLen > 0)
{
if (startPosition <= endPos)
{
if (!clonedProvider.RemoveAt(startPosition, endPos, out this.caretTestPos, out tempHint))
{
OnMaskInputRejected(new MaskInputRejectedEventArgs(this.caretTestPos, tempHint));
}
if (hint == MaskedTextResultHint.NoEffect && hint != tempHint)
{
hint = tempHint;
}
}
}
}
bool updateText = TextOutput != clonedProvider.ToString();
this.maskedTextProvider = clonedProvider;
if( updateText )
{
SetText();
this.caretTestPos = startPosition;
base.SelectInternal( this.caretTestPos, 0, this.maskedTextProvider.Length );
}
else
{
this.caretTestPos = currentCaretPos;
}
return;
}
private void PasteInt( string text )
{
Debug.Assert( !this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided." );
int selStart, selLength;
base.GetSelectionStartAndLength(out selStart, out selLength);
if( string.IsNullOrEmpty(text) )
{
Delete( Keys.Delete, selStart, selLength );
}
else
{
Replace(text, selStart, selLength);
}
}
private object PerformTypeValidation(CancelEventArgs e)
{
object parseRetVal = null;
if (this.validatingType != null)
{
string message = null;
if (!this.flagState[IS_NULL_MASK]&& this.maskedTextProvider.MaskCompleted == false)
{
message = SR.GetString(SR.MaskedTextBoxIncompleteMsg);
}
else
{
string textValue;
if( !this.flagState[IS_NULL_MASK])
{
textValue = this.maskedTextProvider.ToString(/*includePrompt*/ false, this.IncludeLiterals);
}
else
{
textValue = base.Text;
}
try
{
parseRetVal = Formatter.ParseObject(
textValue,
this.validatingType,
typeof(string),
null,
null,
this.formatProvider,
null,
Formatter.GetDefaultDataSourceNullValue(this.validatingType));
}
catch (Exception exception)
{
if (ClientUtils.IsSecurityOrCriticalException(exception))
{
throw;
}
if (exception.InnerException != null)
{
exception = exception.InnerException;
}
message = exception.GetType().ToString() + ": " + exception.Message;
}
}
bool isValidInput = false;
if (message == null)
{
isValidInput = true;
message = SR.GetString(SR.MaskedTextBoxTypeValidationSucceeded);
}
TypeValidationEventArgs tve = new TypeValidationEventArgs(this.validatingType, isValidInput, parseRetVal, message);
OnTypeValidationCompleted(tve);
if( e != null )
{
e.Cancel = tve.Cancel;
}
}
return parseRetVal;
}
private bool PlaceChar(char ch, int startPosition, int length, bool overwrite,
out MaskedTextResultHint hint)
{
return PlaceChar(this.maskedTextProvider, ch, startPosition, length, overwrite, out hint );
}
private bool PlaceChar(MaskedTextProvider provider, char ch, int startPosition, int length, bool overwrite,
out MaskedTextResultHint hint)
{
Debug.Assert( !this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided." );
this.caretTestPos = startPosition;
if (startPosition < this.maskedTextProvider.Length)
{
if (length > 0)
{
int endPos = startPosition + length - 1;
return provider.Replace(ch, startPosition, endPos, out this.caretTestPos, out hint);
}
else
{
if (overwrite)
{
return provider.Replace(ch, startPosition, out this.caretTestPos, out hint);
}
else
{
return provider.InsertAt(ch, startPosition, out this.caretTestPos, out hint);
}
}
}
hint = MaskedTextResultHint.UnavailableEditPosition;
return false;
}
[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
bool msgProcessed = base.ProcessCmdKey(ref msg, keyData);
if (!msgProcessed)
{
if ((int)keyData == (int)Shortcut.CtrlA)
{
base.SelectAll();
msgProcessed = true;
}
}
return msgProcessed;
}
[SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)]
protected internal override bool ProcessKeyMessage(ref Message m)
{
bool msgProcessed = base.ProcessKeyMessage(ref m);
if (this.flagState[IS_NULL_MASK])
{
return msgProcessed;
}
if( m.Msg == NativeMethods.WM_CHAR && base.ImeWmCharsToIgnore > 0 ) {
return true;
}
return msgProcessed;
}
private void ResetCulture()
{
this.Culture = CultureInfo.CurrentCulture;
}
[
EditorBrowsable(EditorBrowsableState.Never)
]
public new void ScrollToCaret()
{
}
private void SetMaskedTextProvider( MaskedTextProvider newProvider )
{
SetMaskedTextProvider( newProvider, null);
}
private void SetMaskedTextProvider( MaskedTextProvider newProvider, string textOnInitializingMask )
{
Debug.Assert( newProvider != null, "Initializing from a null MaskProvider ref." );
newProvider.IncludePrompt = this.maskedTextProvider.IncludePrompt;
newProvider.IncludeLiterals = this.maskedTextProvider.IncludeLiterals;
newProvider.SkipLiterals = this.maskedTextProvider.SkipLiterals;
newProvider.ResetOnPrompt = this.maskedTextProvider.ResetOnPrompt;
newProvider.ResetOnSpace = this.maskedTextProvider.ResetOnSpace;
if( this.flagState[IS_NULL_MASK] && textOnInitializingMask == null)
{
this.maskedTextProvider = newProvider;
return;
}
int testPos = 0;
bool raiseOnMaskInputRejected = false;
MaskedTextResultHint hint = MaskedTextResultHint.NoEffect;
MaskedTextProvider oldProvider = this.maskedTextProvider;
bool preserveCharPos = oldProvider.Mask == newProvider.Mask;
string oldText;
if( textOnInitializingMask != null )
{
oldText = textOnInitializingMask;
raiseOnMaskInputRejected = !newProvider.Set( textOnInitializingMask, out testPos, out hint );
}
else
{
oldText = TextOutput;
int assignedCount = oldProvider.AssignedEditPositionCount;
int srcPos = 0;
int dstPos = 0;
while( assignedCount > 0 )
{
srcPos = oldProvider.FindAssignedEditPositionFrom( srcPos, forward );
Debug.Assert( srcPos != MaskedTextProvider.InvalidIndex, "InvalidIndex unexpected at this time." );
if (preserveCharPos)
{
dstPos = srcPos;
}
else
{
dstPos = newProvider.FindEditPositionFrom(dstPos, forward);
if (dstPos == MaskedTextProvider.InvalidIndex)
{
newProvider.Clear();
testPos = newProvider.Length;
hint = MaskedTextResultHint.UnavailableEditPosition;
break;
}
}
if( !newProvider.Replace( oldProvider[srcPos], dstPos, out testPos, out hint ))
{
preserveCharPos = false;
newProvider.Clear();
break;
}
srcPos++;
dstPos++;
assignedCount--;
}
raiseOnMaskInputRejected = !MaskedTextProvider.GetOperationResultFromHint(hint);
}
this.maskedTextProvider = newProvider;
if( this.flagState[IS_NULL_MASK] )
{
this.flagState[IS_NULL_MASK] = false;
}
if( raiseOnMaskInputRejected )
{
OnMaskInputRejected(new MaskInputRejectedEventArgs(testPos, hint));
}
if( newProvider.IsPassword )
{
SetEditControlPasswordChar('\0');
}
EventArgs e = EventArgs.Empty;
if (textOnInitializingMask != null /*changing mask from null*/ || oldProvider.Mask != newProvider.Mask)
{
OnMaskChanged(e);
}
SetWindowText(GetFormattedDisplayString(), oldText != TextOutput, preserveCharPos);
}
private void SetText()
{
SetWindowText(GetFormattedDisplayString(), true, false);
}
private void SetWindowText()
{
SetWindowText(GetFormattedDisplayString(), false, true);
}
private void SetWindowText(string text, bool raiseTextChangedEvent, bool preserveCaret)
{
this.flagState[QUERY_BASE_TEXT] = true;
try
{
if( preserveCaret )
{
this.caretTestPos = this.SelectionStart;
}
WindowText = text;
if( raiseTextChangedEvent )
{
OnTextChanged(EventArgs.Empty);
}
if( preserveCaret )
{
this.SelectionStart = this.caretTestPos;
}
}
finally
{
this.flagState[QUERY_BASE_TEXT] = false;
}
}
private bool ShouldSerializeCulture()
{
return !CultureInfo.CurrentCulture.Equals(this.Culture);
}
[
EditorBrowsable(EditorBrowsableState.Never)
]
public new void Undo()
{
}
public object ValidateText()
{
return PerformTypeValidation(null);
}
private bool WmClear()
{
Debug.Assert( !this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided." );
if( !this.ReadOnly )
{
int selStart, selLength;
base.GetSelectionStartAndLength( out selStart, out selLength );
Delete(Keys.Delete, selStart, selLength);
return true;
}
return false;
}
private bool WmCopy()
{
Debug.Assert( !this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided." );
if (this.maskedTextProvider.IsPassword)
{
return false;
}
string text = GetSelectedText();
try
{
IntSecurity.ClipboardWrite.Assert();
if (text.Length == 0)
{
Clipboard.Clear();
}
else
{
Clipboard.SetText(text);
}
}
catch (Exception ex)
{
if (ClientUtils.IsSecurityOrCriticalException(ex))
{
throw;
}
}
return true;
}
private bool WmImeComposition(ref Message m)
{
Debug.Assert( !this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided." );
#if DEBUG
if (this.ReadOnly || this.maskedTextProvider.IsPassword)
{
Debug.Assert(this.ImeMode == ImeMode.Disable, "IME enabled when in RO or Pwd mode.");
}
#endif
if (ImeModeConversion.InputLanguageTable == ImeModeConversion.KoreanTable)
{
byte imeConvertionType = imeConvertionNone;
if ((m.LParam.ToInt32() & NativeMethods.GCS_COMPSTR) != 0)
{
imeConvertionType = imeConvertionUpdate;
}
else if ((m.LParam.ToInt32() & NativeMethods.GCS_RESULTSTR) != 0)
{
imeConvertionType = imeConvertionCompleted;
}
if (imeConvertionType != imeConvertionNone)
{
if (this.flagState[IME_ENDING_COMPOSITION])
{
return this.flagState[IME_COMPLETING];
}
}
}
return false;
}
private bool WmImeStartComposition()
{
Debug.Assert( !this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided." );
int startPosition, selectionLen;
base.GetSelectionStartAndLength( out startPosition, out selectionLen );
int startEditPos = this.maskedTextProvider.FindEditPositionFrom( startPosition, forward );
if( startEditPos != MaskedTextProvider.InvalidIndex )
{
if (selectionLen > 0 && (ImeModeConversion.InputLanguageTable == ImeModeConversion.KoreanTable))
{
int endEditPos = this.maskedTextProvider.FindEditPositionFrom(startPosition + selectionLen - 1, backward);
if (endEditPos >= startEditPos)
{
selectionLen = endEditPos - startEditPos + 1;
Delete(Keys.Delete, startEditPos, selectionLen);
}
else
{
ImeComplete();
OnMaskInputRejected(new MaskInputRejectedEventArgs(startPosition, MaskedTextResultHint.UnavailableEditPosition));
return true;
}
}
if( startPosition != startEditPos )
{
this.caretTestPos = startEditPos;
this.SelectionStart = this.caretTestPos;
}
this.SelectionLength = 0;
}
else
{
ImeComplete();
OnMaskInputRejected(new MaskInputRejectedEventArgs(startPosition, MaskedTextResultHint.UnavailableEditPosition));
return true;
}
return false;
}
private void WmPaste()
{
Debug.Assert( !this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided." );
if( this.ReadOnly )
{
return;
}
string text;
try
{
IntSecurity.ClipboardRead.Assert();
text = Clipboard.GetText();
}
catch (Exception ex)
{
if (ClientUtils.IsSecurityOrCriticalException(ex))
{
throw;
}
Debug.Fail(ex.ToString());
return;
}
PasteInt( text );
}
private void WmPrint(ref Message m) {
base.WndProc(ref m);
if ((NativeMethods.PRF_NONCLIENT & unchecked( (int) (long)m.LParam)) != 0 && Application.RenderWithVisualStyles && this.BorderStyle == BorderStyle.Fixed3D) {
IntSecurity.UnmanagedCode.Assert();
try {
using (Graphics g = Graphics.FromHdc(m.WParam)) {
Rectangle rect = new Rectangle(0, 0, this.Size.Width - 1, this.Size.Height - 1);
using (Pen pen = new Pen(VisualStyleInformation.TextControlBorder)) {
g.DrawRectangle(pen, rect);
}
rect.Inflate(-1, -1);
g.DrawRectangle(SystemPens.Window, rect);
}
}
finally {
CodeAccessPermission.RevertAssert();
}
}
}
[SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)]
protected override void WndProc(ref Message m)
{
switch (m.Msg)
{
case NativeMethods.WM_PRINT:
WmPrint(ref m);
return;
case NativeMethods.WM_CONTEXTMENU:
case NativeMethods.EM_CANUNDO:
base.ClearUndo();
base.WndProc(ref m);
return;
case NativeMethods.EM_SCROLLCARET:
case NativeMethods.EM_LIMITTEXT:
case NativeMethods.EM_UNDO:
case NativeMethods.WM_UNDO:
return;
default:
break;
}
if( this.flagState[IS_NULL_MASK])
{
base.WndProc(ref m);
return;
}
switch (m.Msg)
{
case NativeMethods.WM_IME_STARTCOMPOSITION:
if( WmImeStartComposition() )
{
break;
}
goto default;
case NativeMethods.WM_IME_ENDCOMPOSITION:
this.flagState[IME_ENDING_COMPOSITION] = true;
goto default;
case NativeMethods.WM_IME_COMPOSITION:
if( WmImeComposition( ref m ) )
{
break;
}
goto default;
case NativeMethods.WM_CUT:
if (!this.ReadOnly && WmCopy())
{
WmClear();
}
break;
case NativeMethods.WM_COPY:
WmCopy();
break;
case NativeMethods.WM_PASTE:
WmPaste();
break;
case NativeMethods.WM_CLEAR:
WmClear();
break;
case NativeMethods.WM_KILLFOCUS:
base.WndProc(ref m);
WmKillFocus();
break;
case NativeMethods.WM_SETFOCUS:
WmSetFocus();
base.WndProc(ref m);
break;
default:
base.WndProc(ref m);
break;
}
}
private void WmKillFocus()
{
Debug.Assert( !this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided." );
base.GetSelectionStartAndLength( out this.caretTestPos, out this.lastSelLength );
if (this.HidePromptOnLeave && !this.MaskFull)
{
SetWindowText();
base.SelectInternal( this.caretTestPos, this.lastSelLength, this.maskedTextProvider.Length );
}
}
private void WmSetFocus()
{
Debug.Assert( !this.flagState[IS_NULL_MASK], "This method must be called when a Mask is provided." );
if (this.HidePromptOnLeave && !this.MaskFull)
{
SetWindowText();
}
base.SelectInternal( this.caretTestPos, this.lastSelLength, this.maskedTextProvider.Length );
}
}
}
|
|
|
|
|
Date :
2018-07-10 11:50:57 |
By :
ผ่านทางมา |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
โอ้มายาวมากเลย ขอบคุณมากๆเลย ที่ให้ความรู้เพิ่มครับ ขอคอนเวิทเป็น vb ก่อนนะครับ555+
|
|
|
|
|
Date :
2018-07-10 13:12:19 |
By :
ชรินทร์ |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
เท่าที่ผมเขียนโปรแกรมโดยใช้ VB.Net มา ผมแนะนำให้ใช้ DateTimePicker นะครับ (เห็นด้วยกับผู้ตอบ No.4 นะ) มันสามารถลดปัญหาการเกิดข้อผิดพลาดในการป้อนเวลาได้เยอะเลย ลองไปศึกษาคอนโทรลตัวนี้นะครับ
แต่ถ้าผู้ตั้งกระทู้ได้รับโจทย์มาให้ใช้ TextBox หรือ Mask TextBox อาจจะต้องเขียนดักข้อผิดพลาดเยอะกว่า คอนโทรล DateTimePicker (ความคิดเห็นส่วนตัวของผม)
|
|
|
|
|
Date :
2018-07-10 20:30:18 |
By :
Rashun |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
ลองกำหนด textmode ดูครับ
<asp:TextBox ID="txt_01" TextMode="Date" runat="server"></asp:TextBox>
----------------------------------------
อันนี้ด้านหลัง แปลง text เป็น date time ลองเอาไปใช้ดูครับ
DateTime txt_01;
Insert_date = Convert.ToDateTime(txt_01.Text);
|
|
|
|
|
Date :
2018-09-25 16:30:13 |
By :
chetlove08 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
แนะนำให้ศึกษา HTML5 ครับ
<input type="time" > แค่นี้ ก็ ok แล้วครับ
แถม รูปแบบการคีย์ ก็ขึ้นอยู่กับ รูปแบบ ของเครื่อง client เอง
ส่วน รูปแบบที่เราได้รับ ก็เป็นรูปแบบ มาตรฐาน 23:59:59
ถ้าเป็น type="date" 2018-12-31
browser ก็รองรับ ทุก browser
|
|
|
|
|
Date :
2018-09-25 17:22:39 |
By :
Chaidhanan |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Load balance : Server 01
|