【问题标题】:VB.NET Inputbox - How to identify when the Cancel Button is pressed?VB.NET 输入框 - 如何识别何时按下取消按钮?
【发布时间】:2022-05-13 16:57:17
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: vb.net


    【解决方案1】:

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

    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
    

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

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

    【讨论】:

      【解决方案2】:
      input = InputBox("Text:")
      
      If input <> "" Then
         ' Normal
      Else
         ' Cancelled, or empty
      End If
      

      来自MSDN

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

      【讨论】:

      • 这可行,但有没有办法区分取消按钮按下或空确定? (就像 Jamie 在下面发布的那样,但在某种程度上适用于 .NET)
      • 输入框非常有限,正如Jamie所说,改写自己的对话框就好了。
      【解决方案3】:

      我知道这是一个很老的话题,但正确的答案还没有在这里。

      接受的答案与空格一起使用,但用户可以删除此空格 - 因此此答案不可靠。 Georg 的答案有效,但过于复杂。

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

      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
      

      【讨论】:

      • 这对我有用。我不确定我是否完全理解为什么。是不是因为String.Empty和空字符串""不一样?
      • 这段代码不是检查String.Empty的值,而是检查Instance。
      • 这对我不起作用——我为输入框分配了一个默认值,当我删除它并点击 OK 时,这里的 IF 语句返回 true
      • 对我来说,它还检测到一个空输入作为取消。
      【解决方案4】:

      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) 在表单加载事件中放这个(使变量 intInputBoxCancel = 取消事件)

      intInputBoxCancel = StrPtr(String.Empty)    
      

      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
      

      【讨论】:

      • 对于 64 位,我必须使用 Int64 而不是 Integer。但它不起作用,将空输入视为取消按钮。
      • 此方法不再适用于 Microsoft.VisualBasic 命名空间中较新的 InputBox。真正知道是否选择了 Cancel 或 Ok 的唯一方法是创建您自己的 InputBox 函数。
      • 旧的 InputBox 是什么?最新的 .NET Frameworks 中是否仍然可用?
      • 它是 Microsoft.VisualBasic 命名空间的一部分(在参考资料中)。如果您需要差异,最好只创建您自己的 InputBox 控件。这很容易。
      • 新的不起作用的是Microsoft.VisualBasic,不是吗?我想知道这段代码确实适用于旧版本。
      【解决方案5】:

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

      input = InputBox("Text:")
      
      If String.IsNullOrEmpty(input) Then
         ' Cancelled, or empty
      Else
         ' Normal
      End If
      

      【讨论】:

      • 无法区分空值和取消操作吗?
      • 这不起作用。它将取消按钮和空输入都检测为取消,因为两者都是空字符串。
      【解决方案6】:

      您可以使用DialogResult.cancel 方法以更简单的方式进行操作。

      例如:

      Dim anInput as String = InputBox("Enter your pin")
      
      If anInput <>"" then
      
         ' Do something
      Elseif DialogResult.Cancel then
      
        Msgbox("You've canceled")
      End if
      

      【讨论】:

      • 在 DialogResult 上出现运行时错误“424”:需要对象。
      • 我得到了取消结果,既按取消,又按确定不输入任何内容。
      【解决方案7】:

      根据@Theo69 的回答,以下内容对我有用:

      Dim answer As String = Nothing
      answer = InputBox("Your answer")
      If answer is Nothing Then
          'User clicked the Cancel button.
      End If
      

      【讨论】:

        【解决方案8】:

        根据@Theo69 的回答,以下内容对我有用:

            Dim Answer As String = InputBox("Question", DefaultResponse:=vbCr)
            If Answer = "" Then
                'User pressed cancel
            ElseIf Answer = vbcr Then
                'User pressed ok with an empty string in the box
            Else
                'User gave an answer
                Dim Response As String = Answer.Replace(vbCr, "")
            End If
        

        我使用回车是因为我不喜欢在文本框中看到字符。

        【讨论】:

          【解决方案9】:

          大家记住,你可以使用 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
          

          【讨论】:

          • 使用Try..Catch 验证输入通常是不好的做法。它几乎总是能更好地验证您的输入并使用Try..Catch 来处理未知
          • 这不区分取消和空输入。两者都抛出异常。
          【解决方案10】:

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

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

          【讨论】:

          • 这不起作用。取消按钮和空输入都返回长度为 0 的字符串。
          【解决方案11】:

          虽然这个问题是 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
          

          【讨论】:

          • StrPtr 在 VB.NET 中不可用。
          • 抱歉什么意思?就我使用的代码而言,它可以工作。
          【解决方案12】:
          Dim input As String
          
          input = InputBox("Enter something:")
          
          If StrPtr(input) = 0 Then
             MsgBox "You pressed cancel!"
          Elseif input.Length = 0 Then
             MsgBox "OK pressed but nothing entered."
          Else
             MsgBox "OK pressed: value= " & input
          End If
          

          【讨论】:

          • 这是我在概念上寻找的,但 StrPtr 在 VB.NET 中无效
          【解决方案13】:

          为什么不检查是否无效?

          if not inputbox("bleh") = nothing then
          'Code
          else
          ' Error
          end if
          

          这是我通常使用的,因为它更容易阅读。

          【讨论】:

          • 没有什么与用户单击取消时返回的空字符串不同。
          • 这不起作用,因为 InputBox 在取消时返回一个空字符串,而不是 Nothing
          【解决方案14】:
          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
          

          【讨论】:

          • 我不熟悉 VB 风格指南,答案中没有缩进,但我尝试恢复格式化中丢失的内容(以及复制和粘贴?)
          • userReply &lt;&gt; ""userReply.Length = 0在什么条件下可以?
          • 这不起作用。空输入上的取消按钮和 OK 都转到 If 语句的同一分支。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多