Public Shared Function StringToDate(ByVal strDate As String, ByVal Date_Format As String, Optional ByVal Era_Type As String = "en-US") As Date
Dim dRet As Date
Return If(Date.TryParseExact(strDate, Date_Format, New CultureInfo(Era_Type), DateTimeStyles.None, dRet), dRet, Nothing)
End Function
Caller Code (VB.NET)
Dim str2Date1 = StringToDate("31/12/2015", "dd/MM/yyyy", "en-US") --> 12/31/2015
Dim str2Date2 = StringToDate("31/12/2558", "dd/MM/yyyy", "th-TH") --> 12/31/2015
วันเวลาไทย = "2559/12/31 08:30:20 AM +7"
วันเวลา US = "2016/12/31 15:30:20 AM -7"
Code (VB.NET)
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim str2Date1 = StringToDate("2559/12/31 08:30:20 AM +7", "dd/MM/yyyy", "th-TH")
Dim dateNow As Date = Date.Parse(str2Date1)
Me.Text = "The date and time are UTC =>" & TimeZoneInfo.ConvertTimeToUtc(dateNow)
End Sub
Public Shared Function StringToDate(ByVal strDate As String, ByVal Date_Format As String, Optional ByVal Era_Type As String = "en-US") As Date
Dim dRet As Date
Return If(Date.TryParseExact(strDate, Date_Format, New CultureInfo(Era_Type), DateTimeStyles.None, dRet), dRet, Nothing)
End Function
End Class
Dim s As New System.Text.StringBuilder()
s.Append(" 2016/12 4 นา 12/13 12.13 หำ 6 กิโล มี (Jan. 13, 2012) Feb. 12, 12 – น้อย ")
s.Append(" January 15, 1999 July 15, 2923 June 2 2343 7/25/23 08/22/3323 มก. 33, 2333 ")
Dim p01 As String = "(?:(\d{1,2})/(\d{1,2})/(\d{2,4}))"
Dim p02 As String = "(?:(\s\d{1,2})\s+(jan(?:uary){0,1}\.{0,1}|feb(?:ruary){0,1}\.{0,1}|mar(?:ch){0,1}\.{0,1}|apr(?:il){0,1}\.{0,1}|may\.{0,1}|jun(?:e){0,1}\.{0,1}|jul(?:y){0,1}\.{0,1}|aug(?:ust){0,1}\.{0,1}|sep(?:tember){0,1}\.{0,1}|oct(?:ober){0,1}\.{0,1}|nov(?:ember){0,1}\.{0,1}|dec(?:ember){0,1}\.{0,1})\s+(\d{2,4}))"
Dim p03 As String = "(?:(jan(?:uary){0,1}\.{0,1}|feb(?:ruary){0,1}\.{0,1}|mar(?:ch){0,1}\.{0,1}|apr(?:il){0,1}\.{0,1}|may\.{0,1}|jun(?:e){0,1}\.{0,1}|jul(?:y){0,1}\.{0,1}|aug(?:ust){0,1}\.{0,1}|sep(?:tember){0,1}\.{0,1}|oct(?:ober){0,1}\.{0,1}|nov(?:ember){0,1}\.{0,1}|dec(?:ember){0,1}\.{0,1})\s+([0-9]{1,2})[\s,]+(\d{2,4}))"
Dim p04 As String = "(?:(มก(?:ราคม){0,1}\.{0,1}|กุม(?:ภาพันธ์){0,1}\.{0,1}|มี(?:นายน){0,1}\.{0,1}|เม(?:ษายน){0,1}\.{0,1}|พฤ(?:ษภาคม){0,1}\.{0,1}|มิ(?:ถุนายน){0,1}\.{0,1}|กรก(?:ฏาคม){0,1}\.{0,1}|สิง(?:หายน){0,1}\.{0,1}|กัน(?:ยายน){0,1}\.{0,1}|ตุ(?:ลาคม){0,1}\.{0,1}|พฤศ(?:จิกายน){0,1}\.{0,1}|ธัน(?:วาคม){0,1}\.{0,1})\s+([0-9]{1,2})[\s,]+(\d{2,4}))"
Dim p05 As String = "(?:(\d{1,2})/(\d{2,4}))" 'เดือน/ปี
Dim p06 As String = "(?:(\d{2,4})/(\d{1,2}))" 'ปี/เดือน
Dim p07 As String = "(?:(\d{1,2})-(\d{2,4}))" 'เดือน-ปี
Dim p08 As String = "(?:(\d{2,4})-(\d{1,2}))" 'ปี-เดือน
'...
'...
'...
'More...
Dim mc As MatchCollection = Regex.Matches(s.ToString(), p01 + "|" + p02 + "|" + p03 + "|" + p04 + "|" + p05 + "|" + p06 + "|" + p07 + "|" + p08, RegexOptions.IgnoreCase Or RegexOptions.IgnorePatternWhitespace)
Dim lstPattern = {New With {.Name = "Jan", .Value = "01"},
New With {.Name = "Jan.", .Value = "01"},
New With {.Name = "January", .Value = "01"},
New With {.Name = "ม.ค.", .Value = "01"},
New With {.Name = "มกราคม", .Value = "01"}
}
Dim lstSeparator = New Char() {"-"c, "/"c, "."c}
Dim strArray = "นา-หำ/มี.น้อย".Split(lstSeparator)
Dim sPattern = lstPattern.ToList().FindAll(Function(x) x.Name = "MatchCollection Value").FirstOrDefault()
MsgBox(mc.Count)
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Text
Imports System.Windows.Forms
Imports System.Reflection
<ToolboxBitmap(GetType(System.Windows.Forms.ComboBox)), ToolboxItem(True), ToolboxItemFilter("System.Windows.Forms"), Description("Displays an editable text box with a drop-down list of permitted values.")> _
Partial Public Class myComboBox
Inherits System.Windows.Forms.ComboBox
Public Sub New()
InitializeComponent()
End Sub
Private Shared _modalMenuFilter As Type
Private Shared ReadOnly Property modalMenuFilter() As Type
Get
If _modalMenuFilter Is Nothing Then
_modalMenuFilter = Type.[GetType]("System.Windows.Forms.ToolStripManager+ModalMenuFilter")
End If
If _modalMenuFilter Is Nothing Then
_modalMenuFilter = New List(Of Type)(GetType(ToolStripManager).Assembly.GetTypes()).Find(Function(type__1) type__1.FullName = "System.Windows.Forms.ToolStripManager+ModalMenuFilter")
End If
Return _modalMenuFilter
End Get
End Property
Private Shared _suspendMenuMode As MethodInfo
Private Shared ReadOnly Property suspendMenuMode() As MethodInfo
Get
If _suspendMenuMode Is Nothing Then
Dim t As Type = modalMenuFilter
If t IsNot Nothing Then
_suspendMenuMode = t.GetMethod("SuspendMenuMode", BindingFlags.[Static] Or BindingFlags.NonPublic Or BindingFlags.[Public])
End If
End If
Return _suspendMenuMode
End Get
End Property
Private Shared Sub SuspendMenuModeX()
Dim suspendMenuMode__1 As MethodInfo = myComboBox.suspendMenuMode
If suspendMenuMode__1 IsNot Nothing Then
suspendMenuMode__1.Invoke(Nothing, Nothing)
End If
End Sub
Private Shared _resumeMenuMode As MethodInfo
Private Shared ReadOnly Property resumeMenuMode() As MethodInfo
Get
If _resumeMenuMode Is Nothing Then
Dim t As Type = modalMenuFilter
If t IsNot Nothing Then
_resumeMenuMode = t.GetMethod("ResumeMenuMode", BindingFlags.[Static] Or BindingFlags.NonPublic Or BindingFlags.[Public])
End If
End If
Return _resumeMenuMode
End Get
End Property
Private Shared Sub ResumeMenuModeX()
Dim resumeMenuMode__1 As MethodInfo = myComboBox.resumeMenuMode
If resumeMenuMode__1 IsNot Nothing Then
resumeMenuMode__1.Invoke(Nothing, Nothing)
End If
End Sub
Protected Overrides Sub OnDropDown(e As EventArgs)
MyBase.OnDropDown(e)
SuspendMenuModeX()
End Sub
Protected Overrides Sub OnDropDownClosed(e As EventArgs)
ResumeMenuModeX()
MyBase.OnDropDownClosed(e)
End Sub
End Class
อันนี้เอาของฝรั่งมายำ
Code (VB.NET)
Imports System.Drawing
Imports System.Runtime.InteropServices
Imports System.Windows.Forms
Imports System.Security
Imports System.Security.Permissions
Friend NotInheritable Class NativeMethods
Private Sub New()
End Sub
Private Shared HWND_TOPMOST As New HandleRef(Nothing, New IntPtr(-1))
Friend Const WM_NCHITTEST As Integer = &H84,
WM_NCACTIVATE As Integer = &H86,
WS_EX_TRANSPARENT As Integer = &H20,
WS_EX_TOOLWINDOW As Integer = &H80,
WS_EX_LAYERED As Integer = &H80000,
WS_EX_NOACTIVATE As Integer = &H8000000,
HTTRANSPARENT As Integer = -1,
HTLEFT As Integer = 10, HTRIGHT As Integer = 11,
HTTOP As Integer = 12, HTTOPLEFT As Integer = 13,
HTTOPRIGHT As Integer = 14,
HTBOTTOM As Integer = 15,
HTBOTTOMLEFT As Integer = 16,
HTBOTTOMRIGHT As Integer = 17,
WM_PRINT As Integer = &H317,
WM_USER As Integer = &H400,
WM_REFLECT As Integer = WM_USER + &H1C00,
WM_COMMAND As Integer = &H111,
CBN_DROPDOWN As Integer = 7,
WM_GETMINMAXINFO As Integer = &H24
<Flags> _
Friend Enum AnimationFlags As Integer
Roll = &H0
' Uses a roll animation.
HorizontalPositive = &H1
' Animates the window from left to right. This flag can be used with roll or slide animation.
HorizontalNegative = &H2
' Animates the window from right to left. This flag can be used with roll or slide animation.
VerticalPositive = &H4
' Animates the window from top to bottom. This flag can be used with roll or slide animation.
VerticalNegative = &H8
' Animates the window from bottom to top. This flag can be used with roll or slide animation.
Center = &H10
' Makes the window appear to collapse inward if Hide is used or expand outward if the Hide is not used.
Hide = &H10000
' Hides the window. By default, the window is shown.
Activate = &H20000
' Activates the window.
Slide = &H40000
' Uses a slide animation. By default, roll animation is used.
Blend = &H80000
' Uses a fade effect. This flag can be used only with a top-level window.
Mask = &HFFFFF
End Enum
<SuppressUnmanagedCodeSecurity> _
<DllImport("user32.dll", CharSet:=CharSet.Auto)> _
Private Shared Function AnimateWindow(windowHandle As HandleRef, time As Integer, flags As AnimationFlags) As Integer
End Function
Friend Shared Sub AnimateWindow(control As Control, time As Integer, flags As AnimationFlags)
Try
Dim sp As New SecurityPermission(SecurityPermissionFlag.UnmanagedCode)
sp.Demand()
AnimateWindow(New HandleRef(control, control.Handle), time, flags)
Catch generatedExceptionName As SecurityException
End Try
End Sub
<SuppressUnmanagedCodeSecurity> _
<DllImport("user32.dll", CharSet:=CharSet.Auto, ExactSpelling:=True)> _
Private Shared Function SetWindowPos(hWnd As HandleRef, hWndInsertAfter As HandleRef, x As Integer, y As Integer, cx As Integer, cy As Integer, _
flags As Integer) As Boolean
End Function
Friend Shared Sub SetTopMost(control As Control)
Try
Dim sp As New SecurityPermission(SecurityPermissionFlag.UnmanagedCode)
sp.Demand()
SetWindowPos(New HandleRef(control, control.Handle), HWND_TOPMOST, 0, 0, 0, 0, _
&H13)
Catch generatedExceptionName As SecurityException
End Try
End Sub
Friend Shared Function HIWORD(n As Integer) As Integer
Return CShort((n >> 16) And &HFFFF)
End Function
Friend Shared Function HIWORD(n As IntPtr) As Integer
Return HIWORD(CInt(CLng(n)))
End Function
Friend Shared Function LOWORD(n As Integer) As Integer
Return CShort(n And &HFFFF)
End Function
Friend Shared Function LOWORD(n As IntPtr) As Integer
Return LOWORD(CInt(CLng(n)))
End Function
<StructLayout(LayoutKind.Sequential)> _
Friend Structure MINMAXINFO
Public reserved As Point
Public maxSize As Size
Public maxPosition As Point
Public minTrackSize As Size
Public maxTrackSize As Size
End Structure
Private Shared _isRunningOnMono As System.Nullable(Of Boolean)
Public Shared ReadOnly Property IsRunningOnMono() As Boolean
Get
If Not _isRunningOnMono.HasValue Then
_isRunningOnMono = Type.[GetType]("Mono.Runtime") IsNot Nothing
End If
Return _isRunningOnMono.Value
End Get
End Property
End Class
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Drawing.Drawing2D
Imports System.Text
Imports System.Windows.Forms
Imports System.Security.Permissions
Imports System.Runtime.InteropServices
Imports VS = System.Windows.Forms.VisualStyles
<CLSCompliant(True), ToolboxItem(False)> _
Partial Public Class Popup
Inherits ToolStripDropDown
#Region " Fields & Properties "
''' <summary>
''' Gets the content of the pop-up.
''' </summary>
Public Property Content() As Control
Get
Return m_Content
End Get
Private Set(value As Control)
m_Content = value
End Set
End Property
Private m_Content As Control
''' <summary>
''' Determines which animation to use while showing the pop-up window.
''' </summary>
Public Property ShowingAnimation() As PopupAnimations
Get
Return m_ShowingAnimation
End Get
Set(value As PopupAnimations)
m_ShowingAnimation = value
End Set
End Property
Private m_ShowingAnimation As PopupAnimations
''' <summary>
''' Determines which animation to use while hiding the pop-up window.
''' </summary>
Public Property HidingAnimation() As PopupAnimations
Get
Return m_HidingAnimation
End Get
Set(value As PopupAnimations)
m_HidingAnimation = value
End Set
End Property
Private m_HidingAnimation As PopupAnimations
''' <summary>
''' Determines the duration of the animation.
''' </summary>
Public Property AnimationDuration() As Integer
Get
Return m_AnimationDuration
End Get
Set(value As Integer)
m_AnimationDuration = value
End Set
End Property
Private m_AnimationDuration As Integer
''' <summary>
''' Gets or sets a value indicating whether the content should receive the focus after the pop-up has been opened.
''' </summary>
''' <value><c>true</c> if the content should be focused after the pop-up has been opened; otherwise, <c>false</c>.</value>
''' <remarks>If the FocusOnOpen property is set to <c>false</c>, then pop-up cannot use the fade effect.</remarks>
Public Property FocusOnOpen() As Boolean
Get
Return m_FocusOnOpen
End Get
Set(value As Boolean)
m_FocusOnOpen = value
End Set
End Property
Private m_FocusOnOpen As Boolean
''' <summary>
''' Gets or sets a value indicating whether pressing the alt key should close the pop-up.
''' </summary>
''' <value><c>true</c> if pressing the alt key does not close the pop-up; otherwise, <c>false</c>.</value>
Public Property AcceptAlt() As Boolean
Get
Return m_AcceptAlt
End Get
Set(value As Boolean)
m_AcceptAlt = value
End Set
End Property
Private m_AcceptAlt As Boolean
Private _host As ToolStripControlHost
Private _opener As Control
Private _ownerPopup As Popup
Private _childPopup As Popup
Private _resizableTop As Boolean
Private _resizableLeft As Boolean
Private _isChildPopupOpened As Boolean
Private _resizable As Boolean
''' <summary>
''' Gets or sets a value indicating whether the <see cref="PopupControl.Popup" /> is resizable.
''' </summary>
''' <value><c>true</c> if resizable; otherwise, <c>false</c>.</value>
Public Property Resizable() As Boolean
Get
Return _resizable AndAlso Not _isChildPopupOpened
End Get
Set(value As Boolean)
_resizable = value
End Set
End Property
Private _nonInteractive As Boolean
''' <summary>
''' Gets or sets a value indicating whether the <see cref="PopupControl.Popup"></see> acts like a transparent windows (so it cannot be clicked).
''' </summary>
''' <value>
''' <c>true</c> if the popup is noninteractive; otherwise, <c>false</c>.</value>
Public Property NonInteractive() As Boolean
Get
Return _nonInteractive
End Get
Set(value As Boolean)
If value <> _nonInteractive Then
_nonInteractive = value
If IsHandleCreated Then
RecreateHandle()
End If
End If
End Set
End Property
''' <summary>
''' Gets or sets a minimum size of the pop-up.
''' </summary>
''' <returns>An ordered pair of type <see cref="T:System.Drawing.Size" /> representing the width and height of a rectangle.</returns>
Public Shadows Property MinimumSize() As Size
Get
Return m_MinimumSize
End Get
Set(value As Size)
m_MinimumSize = value
End Set
End Property
Private Shadows m_MinimumSize As Size
''' <summary>
''' Gets or sets a maximum size of the pop-up.
''' </summary>
''' <returns>An ordered pair of type <see cref="T:System.Drawing.Size" /> representing the width and height of a rectangle.</returns>
Public Shadows Property MaximumSize() As Size
Get
Return m_MaximumSize
End Get
Set(value As Size)
m_MaximumSize = value
End Set
End Property
Private Shadows m_MaximumSize As Size
''' <summary>
''' Gets parameters of a new window.
''' </summary>
''' <returns>An object of type <see cref="T:System.Windows.Forms.CreateParams" /> used when creating a new window.</returns>
Protected Overrides ReadOnly Property CreateParams() As CreateParams
<SecurityPermission(SecurityAction.LinkDemand, Flags:=SecurityPermissionFlag.UnmanagedCode)> _
Get
Dim cp As CreateParams = MyBase.CreateParams
cp.ExStyle = cp.ExStyle Or NativeMethods.WS_EX_NOACTIVATE
If NonInteractive Then
cp.ExStyle = cp.ExStyle Or NativeMethods.WS_EX_TRANSPARENT Or NativeMethods.WS_EX_LAYERED Or NativeMethods.WS_EX_TOOLWINDOW
End If
Return cp
End Get
End Property
#End Region
#Region " Constructors "
''' <summary>
''' Initializes a new instance of the <see cref="PopupControl.Popup"/> class.
''' </summary>
''' <param name="content">The content of the pop-up.</param>
''' <remarks>
''' Pop-up will be disposed immediately after disposion of the content control.
''' </remarks>
''' <exception cref="T:System.ArgumentNullException"><paramref name="content" /> is <code>null</code>.</exception>
Public Sub New(content__1 As Control)
If content__1 Is Nothing Then
Throw New ArgumentNullException("content")
End If
Content = content__1
FocusOnOpen = True
AcceptAlt = True
ShowingAnimation = PopupAnimations.SystemDefault
HidingAnimation = PopupAnimations.None
AnimationDuration = 100
InitializeComponent()
AutoSize = False
DoubleBuffered = True
ResizeRedraw = True
_host = New ToolStripControlHost(content__1)
Padding = InlineAssignHelper(Margin, InlineAssignHelper(_host.Padding, InlineAssignHelper(_host.Margin, Padding.Empty)))
If NativeMethods.IsRunningOnMono Then
content__1.Margin = Padding.Empty
End If
MinimumSize = content__1.MinimumSize
content__1.MinimumSize = content__1.Size
MaximumSize = content__1.MaximumSize
content__1.MaximumSize = content__1.Size
Size = content__1.Size
If NativeMethods.IsRunningOnMono Then
_host.Size = content__1.Size
End If
TabStop = InlineAssignHelper(content__1.TabStop, True)
content__1.Location = Point.Empty
Items.Add(_host)
AddHandler content__1.Disposed, Sub(sender, e)
content__1 = Nothing
Dispose(True)
End Sub
AddHandler content__1.RegionChanged, Sub(sender, e)
UpdateRegion()
End Sub
AddHandler content__1.Paint, Sub(sender, e)
PaintSizeGrip(e)
End Sub
UpdateRegion()
End Sub
#End Region
#Region " Methods "
''' <summary>
''' Raises the <see cref="E:System.Windows.Forms.ToolStripItem.VisibleChanged"/> event.
''' </summary>
''' <param name="e">An <see cref="T:System.EventArgs"/> that contains the event data.</param>
Protected Overrides Sub OnVisibleChanged(e As EventArgs)
MyBase.OnVisibleChanged(e)
If NativeMethods.IsRunningOnMono Then
Return
End If
' in case of non-Windows
If (Visible AndAlso ShowingAnimation = PopupAnimations.None) OrElse (Not Visible AndAlso HidingAnimation = PopupAnimations.None) Then
Return
End If
Dim flags As NativeMethods.AnimationFlags = If(Visible, NativeMethods.AnimationFlags.Roll, NativeMethods.AnimationFlags.Hide)
Dim _flags As PopupAnimations = If(Visible, ShowingAnimation, HidingAnimation)
If _flags = PopupAnimations.SystemDefault Then
If SystemInformation.IsMenuAnimationEnabled Then
If SystemInformation.IsMenuFadeEnabled Then
_flags = PopupAnimations.Blend
Else
_flags = PopupAnimations.Slide Or (If(Visible, PopupAnimations.TopToBottom, PopupAnimations.BottomToTop))
End If
Else
_flags = PopupAnimations.None
End If
End If
If (_flags And (PopupAnimations.Blend Or PopupAnimations.Center Or PopupAnimations.Roll Or PopupAnimations.Slide)) = PopupAnimations.None Then
Return
End If
If _resizableTop Then
' popup is “inverted”, so the animation must be
If (_flags And PopupAnimations.BottomToTop) <> PopupAnimations.None Then
_flags = (_flags And Not PopupAnimations.BottomToTop) Or PopupAnimations.TopToBottom
ElseIf (_flags And PopupAnimations.TopToBottom) <> PopupAnimations.None Then
_flags = (_flags And Not PopupAnimations.TopToBottom) Or PopupAnimations.BottomToTop
End If
End If
If _resizableLeft Then
' popup is “inverted”, so the animation must be
If (_flags And PopupAnimations.RightToLeft) <> PopupAnimations.None Then
_flags = (_flags And Not PopupAnimations.RightToLeft) Or PopupAnimations.LeftToRight
ElseIf (_flags And PopupAnimations.LeftToRight) <> PopupAnimations.None Then
_flags = (_flags And Not PopupAnimations.LeftToRight) Or PopupAnimations.RightToLeft
End If
End If
flags = flags Or (NativeMethods.AnimationFlags.Mask And DirectCast(CInt(_flags), NativeMethods.AnimationFlags))
NativeMethods.SetTopMost(Me)
NativeMethods.AnimateWindow(Me, AnimationDuration, flags)
End Sub
''' <summary>
''' Processes a dialog box key.
''' </summary>
''' <param name="keyData">One of the <see cref="T:System.Windows.Forms.Keys" /> values that represents the key to process.</param>
''' <returns>
''' true if the key was processed by the control; otherwise, false.
''' </returns>
<UIPermission(SecurityAction.LinkDemand, Window:=UIPermissionWindow.AllWindows)> _
Protected Overrides Function ProcessDialogKey(keyData As Keys) As Boolean
If AcceptAlt AndAlso ((keyData And Keys.Alt) = Keys.Alt) Then
If (keyData And Keys.F4) <> Keys.F4 Then
Return False
Else
Close()
End If
End If
Dim processed As Boolean = MyBase.ProcessDialogKey(keyData)
If Not processed AndAlso (keyData = Keys.Tab OrElse keyData = (Keys.Tab Or Keys.Shift)) Then
Dim backward As Boolean = (keyData And Keys.Shift) = Keys.Shift
Content.SelectNextControl(Nothing, Not backward, True, True, True)
End If
Return processed
End Function
''' <summary>
''' Updates the pop-up region.
''' </summary>
Protected Sub UpdateRegion()
If Region IsNot Nothing Then
Region.Dispose()
Region = Nothing
End If
If Content.Region IsNot Nothing Then
Region = Content.Region.Clone()
End If
End Sub
''' <summary>
''' Shows the pop-up window below the specified control.
''' </summary>
''' <param name="control">The control below which the pop-up will be shown.</param>
''' <remarks>
''' When there is no space below the specified control, the pop-up control is shown above it.
''' </remarks>
''' <exception cref="T:System.ArgumentNullException"><paramref name="control"/> is <code>null</code>.</exception>
Public Overloads Sub Show(control As Control)
If control Is Nothing Then
Throw New ArgumentNullException("control")
End If
Show(control, control.ClientRectangle)
End Sub
''' <summary>
''' Shows the pop-up window below the specified area.
''' </summary>
''' <param name="area">The area of desktop below which the pop-up will be shown.</param>
''' <remarks>
''' When there is no space below specified area, the pop-up control is shown above it.
''' </remarks>
Public Overloads Sub Show(ByVal area As Rectangle)
_resizableTop = InlineAssignHelper(_resizableLeft, False)
Dim location As New Point(area.Left, area.Top + area.Height)
Dim screen__1 As Rectangle = Screen.FromControl(Me).WorkingArea
If location.X + Size.Width > (screen__1.Left + screen__1.Width) Then
_resizableLeft = True
location.X = (screen__1.Left + screen__1.Width) - Size.Width
End If
If location.Y + Size.Height > (screen__1.Top + screen__1.Height) Then
_resizableTop = True
location.Y -= Size.Height + area.Height
End If
'location = control.PointToClient(location);
Show(location, ToolStripDropDownDirection.BelowRight)
End Sub
''' <summary>
''' Shows the pop-up window below the specified area of the specified control.
''' </summary>
''' <param name="control">The control used to compute screen location of specified area.</param>
''' <param name="area">The area of control below which the pop-up will be shown.</param>
''' <remarks>
''' When there is no space below specified area, the pop-up control is shown above it.
''' </remarks>
''' <exception cref="T:System.ArgumentNullException"><paramref name="control"/> is <code>null</code>.</exception>
Public Overloads Sub Show(ByVal control As Control, ByVal area As Rectangle)
If control Is Nothing Then
Throw New ArgumentNullException("control")
End If
SetOwnerItem(control)
_resizableTop = InlineAssignHelper(_resizableLeft, False)
Dim location As Point = control.PointToScreen(New Point(area.Left, area.Top + area.Height))
Dim screen__1 As Rectangle = Screen.FromControl(control).WorkingArea
If location.X + Size.Width > (screen__1.Left + screen__1.Width) Then
_resizableLeft = True
location.X = (screen__1.Left + screen__1.Width) - Size.Width
End If
If location.Y + Size.Height > (screen__1.Top + screen__1.Height) Then
_resizableTop = True
location.Y -= Size.Height + area.Height
End If
location = control.PointToClient(location)
Show(control, location, ToolStripDropDownDirection.BelowRight)
End Sub
Private Sub SetOwnerItem(control As Control)
If control Is Nothing Then
Return
End If
If TypeOf control Is Popup Then
Dim popupControl As Popup = TryCast(control, Popup)
_ownerPopup = popupControl
_ownerPopup._childPopup = Me
OwnerItem = popupControl.Items(0)
Return
ElseIf _opener Is Nothing Then
_opener = control
End If
If control.Parent IsNot Nothing Then
SetOwnerItem(control.Parent)
End If
End Sub
''' <summary>
''' Raises the <see cref="E:System.Windows.Forms.Control.SizeChanged" /> event.
''' </summary>
''' <param name="e">An <see cref="T:System.EventArgs" /> that contains the event data.</param>
Protected Overrides Sub OnSizeChanged(e As EventArgs)
If Content IsNot Nothing Then
Content.MinimumSize = Size
Content.MaximumSize = Size
Content.Size = Size
Content.Location = Point.Empty
End If
MyBase.OnSizeChanged(e)
End Sub
''' <summary>
''' Raises the <see cref="E:System.Windows.Forms.Control.Layout" /> event.
''' </summary>
''' <param name="e">A <see cref="T:System.Windows.Forms.LayoutEventArgs" /> that contains the event data.</param>
Protected Overrides Sub OnLayout(e As LayoutEventArgs)
If Not NativeMethods.IsRunningOnMono Then
MyBase.OnLayout(e)
Return
End If
Dim suggestedSize As Size = GetPreferredSize(Size.Empty)
If AutoSize AndAlso suggestedSize <> Size Then
Size = suggestedSize
End If
SetDisplayedItems()
OnLayoutCompleted(EventArgs.Empty)
Invalidate()
End Sub
''' <summary>
''' Raises the <see cref="E:System.Windows.Forms.ToolStripDropDown.Opening" /> event.
''' </summary>
''' <param name="e">A <see cref="T:System.ComponentModel.CancelEventArgs" /> that contains the event data.</param>
Protected Overrides Sub OnOpening(e As CancelEventArgs)
If Content.IsDisposed OrElse Content.Disposing Then
e.Cancel = True
Return
End If
UpdateRegion()
MyBase.OnOpening(e)
End Sub
''' <summary>
''' Raises the <see cref="E:System.Windows.Forms.ToolStripDropDown.Opened" /> event.
''' </summary>
''' <param name="e">An <see cref="T:System.EventArgs" /> that contains the event data.</param>
Protected Overrides Sub OnOpened(e As EventArgs)
If _ownerPopup IsNot Nothing Then
_ownerPopup._isChildPopupOpened = True
End If
If FocusOnOpen Then
Content.Focus()
End If
MyBase.OnOpened(e)
End Sub
''' <summary>
''' Raises the <see cref="E:System.Windows.Forms.ToolStripDropDown.Closed"/> event.
''' </summary>
''' <param name="e">A <see cref="T:System.Windows.Forms.ToolStripDropDownClosedEventArgs"/> that contains the event data.</param>
Protected Overrides Sub OnClosed(e As ToolStripDropDownClosedEventArgs)
_opener = Nothing
If _ownerPopup IsNot Nothing Then
_ownerPopup._isChildPopupOpened = False
End If
MyBase.OnClosed(e)
End Sub
#End Region
#Region " Resizing Support "
''' <summary>
''' Processes Windows messages.
''' </summary>
''' <param name="m">The Windows <see cref="T:System.Windows.Forms.Message" /> to process.</param>
<SecurityPermission(SecurityAction.LinkDemand, Flags:=SecurityPermissionFlag.UnmanagedCode)> _
Protected Overrides Sub WndProc(ByRef m As Message)
'if (m.Msg == NativeMethods.WM_PRINT && !Visible)
'{
' Visible = true;
'}
If InternalProcessResizing(m, False) Then
Return
End If
MyBase.WndProc(m)
End Sub
''' <summary>
''' Processes the resizing messages.
''' </summary>
''' <param name="m">The message.</param>
''' <returns>true, if the WndProc method from the base class shouldn't be invoked.</returns>
<SecurityPermission(SecurityAction.LinkDemand, Flags:=SecurityPermissionFlag.UnmanagedCode)> _
Public Function ProcessResizing(ByRef m As Message) As Boolean
Return InternalProcessResizing(m, True)
End Function
<SecurityPermission(SecurityAction.LinkDemand, Flags:=SecurityPermissionFlag.UnmanagedCode)> _
Private Function InternalProcessResizing(ByRef m As Message, contentControl As Boolean) As Boolean
If m.Msg = NativeMethods.WM_NCACTIVATE AndAlso m.WParam <> IntPtr.Zero AndAlso _childPopup IsNot Nothing AndAlso _childPopup.Visible Then
_childPopup.Hide()
End If
If Not Resizable AndAlso Not NonInteractive Then
Return False
End If
If m.Msg = NativeMethods.WM_NCHITTEST Then
Return OnNcHitTest(m, contentControl)
ElseIf m.Msg = NativeMethods.WM_GETMINMAXINFO Then
Return OnGetMinMaxInfo(m)
End If
Return False
End Function
<SecurityPermission(SecurityAction.LinkDemand, Flags:=SecurityPermissionFlag.UnmanagedCode)> _
Private Function OnGetMinMaxInfo(ByRef m As Message) As Boolean
Dim minmax As NativeMethods.MINMAXINFO = DirectCast(Marshal.PtrToStructure(m.LParam, GetType(NativeMethods.MINMAXINFO)), NativeMethods.MINMAXINFO)
If Not MaximumSize.IsEmpty Then
minmax.maxTrackSize = MaximumSize
End If
minmax.minTrackSize = MinimumSize
Marshal.StructureToPtr(minmax, m.LParam, False)
Return True
End Function
Private Function OnNcHitTest(ByRef m As Message, contentControl As Boolean) As Boolean
If NonInteractive Then
'm.Result = DirectCast(NativeMethods.HTTRANSPARENT, IntPtr)
m.Result = New IntPtr(NativeMethods.HTTRANSPARENT)
Return True
End If
Dim x As Integer = Cursor.Position.X
' NativeMethods.LOWORD(m.LParam);
Dim y As Integer = Cursor.Position.Y
' NativeMethods.HIWORD(m.LParam);
Dim clientLocation As Point = PointToClient(New Point(x, y))
Dim gripBouns As New GripBounds(If(contentControl, Content.ClientRectangle, ClientRectangle))
Dim transparent As New IntPtr(NativeMethods.HTTRANSPARENT)
If _resizableTop Then
If _resizableLeft AndAlso gripBouns.TopLeft.Contains(clientLocation) Then
'm.Result = If(contentControl, transparent, DirectCast(NativeMethods.HTTOPLEFT, IntPtr))
m.Result = If(contentControl, transparent, New IntPtr(NativeMethods.HTTOPLEFT))
Return True
End If
If Not _resizableLeft AndAlso gripBouns.TopRight.Contains(clientLocation) Then
'm.Result = If(contentControl, transparent, DirectCast(NativeMethods.HTTOPRIGHT, IntPtr))
m.Result = If(contentControl, transparent, New IntPtr(NativeMethods.HTTOPRIGHT))
Return True
End If
If gripBouns.Top.Contains(clientLocation) Then
'm.Result = If(contentControl, transparent, DirectCast(NativeMethods.HTTOP, IntPtr))
m.Result = If(contentControl, transparent, New IntPtr(NativeMethods.HTTOP))
Return True
End If
Else
If _resizableLeft AndAlso gripBouns.BottomLeft.Contains(clientLocation) Then
'm.Result = If(contentControl, transparent, DirectCast(NativeMethods.HTBOTTOMLEFT, IntPtr))
m.Result = If(contentControl, transparent, New IntPtr(NativeMethods.HTBOTTOMLEFT))
Return True
End If
If Not _resizableLeft AndAlso gripBouns.BottomRight.Contains(clientLocation) Then
'm.Result = If(contentControl, transparent, DirectCast(NativeMethods.HTBOTTOMRIGHT, IntPtr))
m.Result = If(contentControl, transparent, New IntPtr(NativeMethods.HTBOTTOMRIGHT))
Return True
End If
If gripBouns.Bottom.Contains(clientLocation) Then
'm.Result = If(contentControl, transparent, DirectCast(NativeMethods.HTBOTTOM, IntPtr))
m.Result = If(contentControl, transparent, New IntPtr(NativeMethods.HTBOTTOM))
Return True
End If
End If
If _resizableLeft AndAlso gripBouns.Left.Contains(clientLocation) Then
'm.Result = If(contentControl, transparent, DirectCast(NativeMethods.HTLEFT, IntPtr))
m.Result = If(contentControl, transparent, New IntPtr(NativeMethods.HTLEFT))
Return True
End If
If Not _resizableLeft AndAlso gripBouns.Right.Contains(clientLocation) Then
'm.Result = If(contentControl, transparent, DirectCast(NativeMethods.HTRIGHT, IntPtr))
m.Result = If(contentControl, transparent, New IntPtr(NativeMethods.HTRIGHT))
Return True
End If
Return False
End Function
Private _sizeGripRenderer As VS.VisualStyleRenderer
''' <summary>
''' Paints the sizing grip.
''' </summary>
''' <param name="e">The <see cref="System.Windows.Forms.PaintEventArgs" /> instance containing the event data.</param>
Public Sub PaintSizeGrip(e As PaintEventArgs)
If e Is Nothing OrElse e.Graphics Is Nothing OrElse Not _resizable Then
Return
End If
Dim clientSize As Size = Content.ClientSize
Using gripImage As New Bitmap(&H10, &H10)
Using g As Graphics = Graphics.FromImage(gripImage)
If Application.RenderWithVisualStyles Then
If _sizeGripRenderer Is Nothing Then
_sizeGripRenderer = New VS.VisualStyleRenderer(VS.VisualStyleElement.Status.Gripper.Normal)
End If
_sizeGripRenderer.DrawBackground(g, New Rectangle(0, 0, &H10, &H10))
Else
ControlPaint.DrawSizeGrip(g, Content.BackColor, 0, 0, &H10, &H10)
End If
End Using
Dim gs As GraphicsState = e.Graphics.Save()
e.Graphics.ResetTransform()
If _resizableTop Then
If _resizableLeft Then
e.Graphics.RotateTransform(180)
e.Graphics.TranslateTransform(-clientSize.Width, -clientSize.Height)
Else
e.Graphics.ScaleTransform(1, -1)
e.Graphics.TranslateTransform(0, -clientSize.Height)
End If
ElseIf _resizableLeft Then
e.Graphics.ScaleTransform(-1, 1)
e.Graphics.TranslateTransform(-clientSize.Width, 0)
End If
e.Graphics.DrawImage(gripImage, clientSize.Width - &H10, clientSize.Height - &H10 + 1, &H10, &H10)
e.Graphics.Restore(gs)
End Using
End Sub
Private Shared Function InlineAssignHelper(Of T)(ByRef target As T, value As T) As T
target = value
Return value
End Function
#End Region
End Class
<ToolboxBitmap(GetType(System.Windows.Forms.ComboBox)), ToolboxItem(True), ToolboxItemFilter("System.Windows.Forms"), Description("Displays an editable text box with a drop-down list of permitted values.")> _
Partial Public Class PopupComboBox
Inherits myComboBox
Public Sub New()
'this.dropDownHideTime = DateTime.UtcNow;
InitializeComponent()
Me.dropDownHideTime = DateTime.UtcNow
MyBase.DropDownHeight = InlineAssignHelper(MyBase.DropDownWidth, 1)
MyBase.IntegralHeight = False
End Sub
Private _dropDown As PopupControl.Popup
Private m_dropDownControl As Control
Public Property DropDownControl() As Control
Get
Return m_dropDownControl
End Get
Set(value As Control)
If m_dropDownControl Is value Then
Return
End If
m_dropDownControl = value
If _dropDown IsNot Nothing Then
RemoveHandler _dropDown.Closed, AddressOf dropDown_Closed
_dropDown.Dispose()
End If
_dropDown = New Popup(value)
AddHandler _dropDown.Closed, AddressOf dropDown_Closed
End Set
End Property
Private dropDownHideTime As DateTime
Private Sub dropDown_Closed(sender As Object, e As ToolStripDropDownClosedEventArgs)
dropDownHideTime = DateTime.UtcNow
End Sub
Public Shadows Property DroppedDown() As Boolean
Get
Return _dropDown.Visible
End Get
Set(value As Boolean)
If DroppedDown Then
HideDropDown()
Else
ShowDropDown()
End If
End Set
End Property
Public Shadows Event DropDown As EventHandler
Public Sub ShowDropDown()
If _dropDown IsNot Nothing Then
If (DateTime.UtcNow - dropDownHideTime).TotalSeconds > 0.5 Then
RaiseEvent DropDown(Me, EventArgs.Empty)
_dropDown.Show(Me)
Else
dropDownHideTime = DateTime.UtcNow.Subtract(New TimeSpan(0, 0, 1))
Focus()
End If
End If
End Sub
Public Shadows Event DropDownClosed As EventHandler
Public Sub HideDropDown()
If _dropDown IsNot Nothing Then
_dropDown.Hide()
RaiseEvent DropDownClosed(Me, EventArgs.Empty)
End If
End Sub
<SecurityPermission(SecurityAction.LinkDemand, Flags:=SecurityPermissionFlag.UnmanagedCode)> _
Protected Overrides Sub WndProc(ByRef m As Message)
If m.Msg = (NativeMethods.WM_COMMAND + NativeMethods.WM_REFLECT) AndAlso NativeMethods.HIWORD(m.WParam) = NativeMethods.CBN_DROPDOWN Then
BeginInvoke(New MethodInvoker(AddressOf ShowDropDown))
Return
End If
MyBase.WndProc(m)
End Sub
End Class