VB.NET Inputbox - How to identify when the Cancel Button is pressed?

前端 未结 12 1739
灰色年华
灰色年华 2021-01-03 22:26

I have a simple windows application that pops up an input box for users to enter in a date to do searches.

How do I identify if the user clicked on the Cancel butt

12条回答
  •  耶瑟儿~
    2021-01-03 23:28

    1) create a Global function (best in a module so that you only need to declare once)

    Imports System.Runtime.InteropServices                 ' required imports
    Public intInputBoxCancel as integer                    ' public variable
    
    Public Function StrPtr(ByVal obj As Object) As Integer
        Dim Handle As GCHandle = GCHandle.Alloc(obj, GCHandleType.Pinned)
        Dim intReturn As Integer = Handle.AddrOfPinnedObject.ToInt32
        Handle.Free()
        Return intReturn
    End Function
    

    2) in the form load event put this (to make the variable intInputBoxCancel = cancel event)

    intInputBoxCancel = StrPtr(String.Empty)    
    

    3) now, you can use anywhere in your form (or project if StrPtr is declared global in module)

    dim ans as string = inputbox("prompt")         ' default data up to you
    if StrPtr(ans) = intInputBoxCancel then
       ' cancel was clicked
    else
       ' ok was clicked (blank input box will still be shown here)
    endif
    

提交回复
热议问题