Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/252.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Vb.net 从代码中单击messagebox_Vb.net_Messagebox - Fatal编程技术网

Vb.net 从代码中单击messagebox

Vb.net 从代码中单击messagebox,vb.net,messagebox,Vb.net,Messagebox,好吧,请不要问为什么,但我真的需要这个 因此,我将向用户显示一个MessageBox 2秒钟,然后我需要自动关闭它,而无需用户输入 Messagebox.Show("RandomStringHere") System.Threading.Thread.Sleep("2000") 我被卡住了。我有什么办法可以做到这一点吗?请不要问为什么,但这确实是必要的 我在网上找不到任何关于这个问题的帮助,所以我想你们可以帮我。创建自己的表单。您可以在设计器中执行此操作,也可以使用下面示例中的代码。设置计时器

好吧,请不要问为什么,但我真的需要这个

因此,我将向用户显示一个MessageBox 2秒钟,然后我需要自动关闭它,而无需用户输入

Messagebox.Show("RandomStringHere")
System.Threading.Thread.Sleep("2000")
我被卡住了。我有什么办法可以做到这一点吗?请不要问为什么,但这确实是必要的


我在网上找不到任何关于这个问题的帮助,所以我想你们可以帮我。

创建自己的表单。您可以在设计器中执行此操作,也可以使用下面示例中的代码。设置计时器并在两秒钟内关闭窗体:

Private _msgForm As Form
Private _tmr As Windows.Forms.Timer

Private Sub Button9_Click(sender As Object, e As EventArgs) Handles Button9.Click

    _msgForm = New Form
    With _msgForm
        .Height = 200
        .Width = 300
        .StartPosition = FormStartPosition.CenterScreen
        .Text = "Message"
    End With

    Dim btn As New Button
    With btn
        .Text = "OK"
        .Top = _msgForm.Height - 75
        .Left = _msgForm.Width - 100
        .Anchor = AnchorStyles.Right Or AnchorStyles.Bottom
    End With
    _msgForm.Controls.Add(btn)

    Dim lbl As New Label
    With lbl
        .Text = "This is the text of the message box"
        .Left = 0
        .Top = 0
        .Width = _msgForm.ClientSize.Width
        .Height = _msgForm.ClientSize.Height - 120
        .Anchor = AnchorStyles.Bottom Or AnchorStyles.Left Or AnchorStyles.Right Or AnchorStyles.Top
    End With
    _msgForm.Controls.Add(lbl)

    _tmr = New Windows.Forms.Timer
    With _tmr
        .Interval = 2000
        .Enabled = True
    End With

    AddHandler _tmr.Tick, AddressOf TimerTick
    AddHandler btn.Click, AddressOf ButtonClick
    _msgForm.ShowDialog()

End Sub

Private Sub TimerTick(sender As Object, e As EventArgs)
    _msgForm.Close()
End Sub

Private Sub ButtonClick(sender As Object, e As EventArgs)
    CType(sender, Button).FindForm.Close()
End Sub
用法示例:

    Using New CenteredMessageBox(Owner:=Me,
                                 TextFont:=Me.Font,
                                 TimeOut:=2500)

        MessageBox.Show("Test Text", 
                        "Test Title", 
                        MessageBoxButtons.OK, 
                        MessageBoxIcon.Information)

    End Using
自定义消息框:

' [ Centered MessageBox ]
' By Elektro
'
' The author of the original idea is Hans Passant: 
' http://stackoverflow.com/questions/2576156/winforms-how-can-i-make-messagebox-appear-centered-on-mainform
'
' Examples :
'
'Using New CenteredMessageBox(Owner:=Me,
'                             TextFont:=New Font("Lucida Console", Font.SizeInPoints, FontStyle.Bold),
'                             TimeOut:=2500)
'
'    MessageBox.Show("Test Text", "Test Title", MessageBoxButtons.OK, MessageBoxIcon.Information)
'
'End Using

#Region " Centered MessageBox Class"

#Region " Imports "

Imports System.Drawing
Imports System.Runtime.InteropServices
Imports System.Text
Imports System.Windows.Forms

#End Region

Class CenteredMessageBox : Implements IDisposable

#Region " Variables, Objects, Properties "

    Private mTries As Integer = 0
    Private mOwner As Form
    Private mFont As Font
    Private mTimeOut As Integer
    Private WithEvents TimeoutTimer As Timer

    Private ReadOnly Property MessageBoxWindowHandle As IntPtr
        Get
            Return _MessageBoxWindowHandle
        End Get
    End Property
    Dim _MessageBoxWindowHandle As IntPtr = IntPtr.Zero


#End Region

#Region " P/Invoke "

    Friend Class NativeMethods

        Friend Const WM_SETFONT As Integer = &H30
        Friend Const WM_GETFONT As Integer = &H31

        Friend Delegate Function EnumThreadWndProc(hWnd As IntPtr, lp As IntPtr) As Boolean

        Friend Declare Function SetWindowPos Lib "user32" (ByVal hwnd As IntPtr, ByVal hWndInsertAfter As IntPtr, ByVal x As Integer, ByVal y As Integer, ByVal cx As Integer, ByVal cy As Integer, ByVal wFlags As UInt32) As Boolean

        <DllImport("user32.dll")>
        Friend Shared Function EnumThreadWindows(tid As Integer, callback As NativeMethods.EnumThreadWndProc, lp As IntPtr) As Boolean
        End Function

        <DllImport("kernel32.dll")>
        Friend Shared Function GetCurrentThreadId() As Integer
        End Function

        <DllImport("user32.dll", CharSet:=CharSet.Unicode)>
        Friend Shared Function GetClassName(hWnd As IntPtr, buffer As StringBuilder, buflen As Integer) As Integer
        End Function

        <DllImport("user32.dll")>
        Friend Shared Function GetDlgItem(hWnd As IntPtr, item As Integer) As IntPtr
        End Function

        <DllImport("user32.dll")>
        Friend Shared Function SendMessage(hWnd As IntPtr, msg As Integer, wp As IntPtr, lp As IntPtr) As IntPtr
        End Function

        <DllImport("user32.dll")>
        Friend Shared Function GetWindowRect(hWnd As IntPtr, ByRef rc As RECT) As Boolean
        End Function

        <DllImport("user32.dll")>
        Friend Shared Function MoveWindow(hWnd As IntPtr, x As Integer, y As Integer, w As Integer, h As Integer, repaint As Boolean) As Boolean
        End Function

        ''' <summary>
        ''' <para>The DestroyWindow function destroys the specified window. The function sends WM_DESTROY and WM_NCDESTROY messages to the window to deactivate it and remove the keyboard focus from it. The function also destroys the window's menu, flushes the thread message queue, destroys timers, removes clipboard ownership, and breaks the clipboard viewer chain (if the window is at the top of the viewer chain).</para>
        ''' <para>If the specified window is a parent or owner window, DestroyWindow automatically destroys the associated child or owned windows when it destroys the parent or owner window. The function first destroys child or owned windows, and then it destroys the parent or owner window.</para>
        ''' <para>DestroyWindow also destroys modeless dialog boxes created by the CreateDialog function.</para>
        ''' </summary>
        ''' <param name="hwnd">Handle to the window to be destroyed.</param>
        ''' <returns>If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error information, call GetLastError.</returns>
        <DllImport("user32.dll", CharSet:=CharSet.Unicode, SetLastError:=True)>
        Friend Shared Function DestroyWindow(hwnd As IntPtr) As <MarshalAs(UnmanagedType.Bool)> Boolean
        End Function

    End Class

    Structure RECT
        Public Left As Integer
        Public Top As Integer
        Public Right As Integer
        Public Bottom As Integer
    End Structure

#End Region

#Region " Constructors "

    ''' <summary>
    ''' Initializes a new instance of the <see cref="CenteredMessageBox"/> class.
    ''' </summary>
    ''' <param name="Owner">Indicates the form that owns this messagebox.</param>
    ''' <param name="TextFont">Indicates the text-font used to display the text label.</param>
    ''' <param name="TimeOut">
    ''' Indicates the timeout, in ms, to auto-close this <see cref="CenteredMessageBox"/>
    ''' Default is '0' which means Infinite.
    ''' </param>
    Public Sub New(ByVal Owner As Form,
                   Optional TextFont As Font = Nothing,
                   Optional TimeOut As Integer = 0I)

        mOwner = Owner
        mFont = TextFont
        mTimeOut = TimeOut
        Owner.BeginInvoke(New MethodInvoker(AddressOf findDialog))

    End Sub

#End Region

#Region " Private MEthods "

    Private Sub findDialog()

        ' Enumerate windows to find the message box
        If mTries < 0 Then
            Return
        End If

        Dim callback As New NativeMethods.EnumThreadWndProc(AddressOf checkWindow)

        If NativeMethods.EnumThreadWindows(NativeMethods.GetCurrentThreadId(), callback, IntPtr.Zero) Then

            If System.Threading.Interlocked.Increment(mTries) < 10 Then
                mOwner.BeginInvoke(New MethodInvoker(AddressOf findDialog))
            End If

        End If

        If mTimeOut > 0 Then
            TimeoutTimer = New Timer With {.Interval = mTimeOut, .Enabled = True}
            TimeoutTimer.Start()
        End If

    End Sub

    Private Function checkWindow(hWnd As IntPtr, lp As IntPtr) As Boolean

        ' Checks if <hWnd> is a dialog
        Dim sb As New StringBuilder(260)
        NativeMethods.GetClassName(hWnd, sb, sb.Capacity)
        If sb.ToString() <> "#32770" Then Return True

        ' Get the STATIC control that displays the text
        Dim hText As IntPtr = NativeMethods.GetDlgItem(hWnd, &HFFFF)
        Me._MessageBoxWindowHandle = hWnd

        Dim frmRect As New Rectangle(mOwner.Location, mOwner.Size)
        Dim dlgRect As RECT
        NativeMethods.GetWindowRect(hWnd, dlgRect)

        If hText <> IntPtr.Zero Then

            If mFont Is Nothing Then
                ' Get the current font
                mFont = Font.FromHfont(NativeMethods.SendMessage(hText, NativeMethods.WM_GETFONT, IntPtr.Zero, IntPtr.Zero))

            ElseIf mFont IsNot Nothing Then
                NativeMethods.SetWindowPos(hText, 0, 70, 35, frmRect.Width, mFont.Height, 0)

            End If

            NativeMethods.SendMessage(hText, NativeMethods.WM_SETFONT, mFont.ToHfont(), New IntPtr(1))

            ' Resize and positionate the messagebox window:
            NativeMethods.MoveWindow(hWnd,
                                     frmRect.Left + (frmRect.Width - dlgRect.Right + dlgRect.Left) \ 2,
                                     frmRect.Top + (frmRect.Height - dlgRect.Bottom + dlgRect.Top) \ 2,
                                     (dlgRect.Right - dlgRect.Left),
                                     (dlgRect.Bottom - dlgRect.Top), True)

        End If

        ' Done
        Return False

    End Function

#End Region

#Region " Event Handlers "

    Private Sub TimeoutTimer_Tick(ByVal sender As Object, ByVal e As EventArgs) Handles TimeoutTimer.Tick

        NativeMethods.DestroyWindow(Me._MessageBoxWindowHandle)
        Me.Dispose()

    End Sub

#End Region

#Region " IDisposable "

    Public Sub Dispose() Implements IDisposable.Dispose
        mTries = -1
        mOwner = Nothing
        If mFont IsNot Nothing Then mFont.Dispose()
    End Sub

#End Region

End Class

#End Region
”[居中消息框]
”埃列克特罗说
'
“最初想法的作者是汉斯·帕桑:
' http://stackoverflow.com/questions/2576156/winforms-how-can-i-make-messagebox-appear-centered-on-mainform
'
例如:
'
'使用新的CenteredMessageBox(所有者:=Me,
'TextFont:=新字体(“Lucida控制台”,Font.SizeInPoints,FontStyle.Bold),
'超时:=2500)
'
'MessageBox.Show(“测试文本”、“测试标题”、MessageBoxButtons.OK、MessageBoxIcon.Information)
'
"终端使用",
#区域“以MessageBox类为中心”
#区域“进口”
导入系统。绘图
导入System.Runtime.InteropServices
导入系统文本
导入System.Windows.Forms
#末端区域
类CenteredMessageBox:实现IDisposable
#区域“变量、对象、属性”
作为整数的私有mTries=0
作为形式的私人割草机
作为字体的专用mFont
私有mTimeOut作为整数
Private WithEvents TimeoutTimer作为计时器
私有只读属性MessageBoxWindowHandle作为IntPtr
得到
Return\u MessageBoxWindowHandle
结束
端属性
Dim\u MessageBoxWindowHandle作为IntPtr=IntPtr.Zero
#末端区域
#区域“P/调用”
Friend类NativeMethods
Friend Const WM_SETFONT作为整数=&H30
Friend Const WM_GETFONT作为整数=&H31
友元委托函数EnumThreadWndProc(hWnd作为IntPtr,lp作为IntPtr)作为布尔值
友元将函数SetWindowPos Lib“user32”(ByVal hwnd作为IntPtr,ByVal hwninsertafter作为IntPtr,ByVal x作为整数,ByVal y作为整数,ByVal cx作为整数,ByVal cy作为整数,ByVal wFlags作为UInt32)声明为布尔值
朋友共享函数EnumThreadWindows(tid为整数,回调为NativeMethods.EnumThreadWndProc,lp为IntPtr)为布尔值
端函数
好友共享函数GetCurrentThreadId()为整数
端函数
朋友共享函数GetClassName(hWnd作为IntPtr,缓冲区作为StringBuilder,buflen作为Integer)作为Integer
端函数
朋友共享函数GetDlgItem(hWnd作为IntPtr,项作为整数)作为IntPtr
端函数
朋友共享函数SendMessage(hWnd作为IntPtr,msg作为Integer,wp作为IntPtr,lp作为IntPtr)作为IntPtr
端函数
朋友共享函数GetWindowRect(hWnd作为IntPtr,ByRef rc作为RECT)作为布尔值
端函数
朋友共享函数MoveWindow(hWnd为IntPtr,x为整数,y为整数,w为整数,h为整数,重绘为布尔值)为布尔值
端函数
''' 
''DestroyWindow函数将销毁指定的窗口。该函数向窗口发送WM_DESTROY和WM_NCDESTROY消息,以停用窗口并从窗口中移除键盘焦点。该函数还将销毁窗口的菜单、刷新线程消息队列、销毁计时器、删除剪贴板所有权并断开剪贴板查看器链(如果窗口位于查看器链的顶部)。
''如果指定的窗口是父窗口或所有者窗口,DestroyWindow会在销毁父窗口或所有者窗口时自动销毁关联的子窗口或所有者窗口。该函数首先销毁子窗口或所有者窗口,然后销毁父窗口或所有者窗口。
''DestroyWindow还销毁CreateDialog函数创建的无模式对话框。
''' 
要销毁的窗口的“”句柄。
''如果函数成功,则返回值为非零。如果函数失败,则返回值为零。要获取扩展错误信息,请调用GetLastError。
朋友共享函数DestroyWindow(hwnd作为IntPtr)作为布尔值
端函数
末级
结构矩形
公共左整数
作为整数的公共Top
作为整数的公权
公共底部为整数
端部结构
#末端区域
#地区“建设者”
''' 
''初始化类的新实例。
''' 
''表示拥有此messagebox的窗体。
''表示用于显示文本标签的文本字体。
''' 
''表示自动关闭此服务器的超时时间(毫秒)
''默认值为'0',表示无限。
''' 
公共子新(ByVal所有者作为表格,
可选文本字体,字体=无,
可选超时(整数=0I)
割草机=所有者
mFont=TextFont
mTimeOut=超时
Owner.BeginInvoke(新方法调用程序(findDialog的地址))
端接头
#末端区域
#区域“私有方法”
私有子findDialog()
'枚举窗口以查找消息框
如果mTries<0,则
返回
如果结束
Dim回调作为新的NativeMethods.EnumThreadWndProc(checkWindow的地址)
如果是NativeMethods.EnumThreadWindows(NativeMethods.GetCurrentThreadId(),回调,IntPtr.Zero),则
如果系统螺纹联锁增量(mTries)<10,则
mOwner.BeginInvoke(新方法调用程序(findDialog的地址))
如果结束
如果结束
如果mTimeOut>0,则
TimeoutTimer=新计时器,带有{.Interval=mTimeOut、.Enabled=True}
TimeoutTimer.Start()
如果结束
端接头
专用函数检查窗口(hWnd As