VB.NET 输入框 - 如何识别何时按下取消按钮?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2923764/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 14:54:00  来源:igfitidea点击:

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

vb.net

提问by The Sasquatch

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

我有一个简单的 Windows 应用程序,它会弹出一个输入框,供用户输入日期进行搜索。

How do I identify if the user clicked on the Cancel button, or merely pressed OK without entering any data as both appear to return the same value?

我如何确定用户是单击“取消”按钮,还是仅按“确定”而不输入任何数据,因为两者似乎都返回相同的值?

I have found some examples of handling this in VB 6 but none of them really function in the .NET world.

我发现了一些在 VB 6 中处理这个问题的例子,但它们都没有在 .NET 世界中真正起作用。

Ideally I would like to know how to handle the empty OK and the Cancel seperately, but I would be totally ok with just a good way to handle the cancel.

理想情况下,我想知道如何分别处理空的 OK 和 Cancel,但我完全可以用一个很好的方法来处理取消。

回答by The Sasquatch

Here is what I did and it worked perfectly for what I was looking to do:

这是我所做的,它非常适合我想要做的事情:

Dim StatusDate As String
 StatusDate = InputBox("What status date do you want to pull?", "Enter Status Date", " ")

        If StatusDate = " " Then
            MessageBox.Show("You must enter a Status date to continue.")
            Exit Sub
        ElseIf StatusDate = "" Then
            Exit Sub
        End If

This key was to set the default value of the input box to be an actual space, so a user pressing just the OK button would return a value of " " while pressing cancel returns ""

这个键是将输入框的默认值设置为一个实际的空格,所以用户只按确定按钮将返回值“ ”,而按取消返回“”

From a usability standpoint, the defaulted value in the input box starts highlighted and is cleared when a user types so the experience is no different than if the box had no value.

从可用性的角度来看,输入框中的默认值开始突出显示,并在用户键入时清除,因此体验与该框没有值时没有什么不同。

回答by Kyle Rozendo

input = InputBox("Text:")

If input <> "" Then
   ' Normal
Else
   ' Cancelled, or empty
End If

From MSDN:

MSDN

If the user clicks Cancel, the function returns a zero-length string ("").

如果用户单击取消,该函数将返回一个零长度字符串 ("")。

回答by Theo69

I know this is a very old topic, but the correct answer is still not here.

我知道这是一个非常古老的话题,但正确答案仍然不在这里。

The accepted answer works with a space, but the user can remove this space - so this answer is not reliable. The answer of Georg works, but is needlessly complex.

接受的答案适用于一个空格,但用户可以删除这个空格 - 所以这个答案是不可靠的。Georg 的答案有效,但不必要地复杂。

To test if the user pressed cancel, just use the following code:

要测试用户是否按下了取消,只需使用以下代码:

Dim Answer As String = InputBox("Question")
If String.ReferenceEquals(Answer, String.Empty) Then
    'User pressed cancel
Else if Answer = "" Then
    'User pressed ok with an empty string in the box
Else
    'User gave an answer

回答by Georg

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

1)创建一个全局函数(最好在一个模块中,这样你只需要声明一次)

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)

2)在表单加载事件中放这个(使变量intInputBoxCancel=cancel事件)

intInputBoxCancel = StrPtr(String.Empty)    

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

3) 现在,您可以在表单中的任何地方使用(如果 StrPtr 在模块中被声明为全局,则可以使用项目)

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

回答by Jgregtheitroade108

I like using the IsNullOrEmpty method of the class String like so...

我喜欢像这样使用 String 类的 IsNullOrEmpty 方法......

input = InputBox("Text:")

If String.IsNullOrEmpty(input) Then
   ' Cancelled, or empty
Else
   ' Normal
End If

回答by C.Aymar

You can do it in a simpler way using the DialogResult.cancelmethod.

您可以使用该DialogResult.cancel方法以更简单的方式完成此操作。

Eg:

例如:

Dim anInput as String = InputBox("Enter your pin")

If anInput <>"" then

   ' Do something
Elseif DialogResult.Cancel then

  Msgbox("You've canceled")
End if

回答by zmd94

Although this question is being asked for 5 years ago. I just want to share my answer. Below is how I detect whether someone is clicked cancel and OK button in input box:

虽然这个问题是 5 年前提出的。我只想分享我的答案。以下是我如何检测是否有人在输入框中单击了取消和确定按钮:

Public sName As String

Sub FillName()
    sName = InputBox("Who is your name?")
    ' User is clicked cancel button
    If StrPtr(sName) = False Then
        MsgBox ("Please fill your name!")
        Exit Sub
    End If

   ' User is clicked OK button whether entering any data or without entering any datas
    If sName = "" Then
        ' If sName string is empty 
        MsgBox ("Please fill your name!")
    Else
        ' When sName string is filled
        MsgBox ("Welcome " & sName & " and nice see you!")
    End If
End Sub

回答by Sidney

Guys remember that you can use the try catch end event

伙计们记得你可以使用 try catch 结束事件

Dim Green as integer

Try
    Green = InputBox("Please enter a value for green")
    Catch ex as Exception
        MsgBox("Green must be a valid integer!")
End Try

回答by Ahmet U?ur

Try this. I've tried the solution and it works.

尝试这个。我已经尝试了解决方案并且它有效。

Dim ask = InputBox("")
If ask.Length <> 0 Then
   // your code
Else
   // cancel or X Button 
End If

回答by Devharsh

Dim userReply As String
userReply = Microsoft.VisualBasic.InputBox("Message")
If userReply = "" Then 
  MsgBox("You did not enter anything. Try again")
ElseIf userReply.Length = 0 Then 
  MsgBox("You did not enter anything")
End If