如何在执行时在任务栏中显示应用程序?

时间:2014-03-03 00:08:50

标签: vb.net task

我的应用程序是单实例应用程序,在关闭时最小化到Windows任务栏。但是,我遇到的一个问题是,当我的应用程序执行时(例如:通过桌面上的快捷方式),同时最小化到任务栏,应用程序不会恢复。相反,应用程序的另一个实例会打开,但当它意识到另一个实例已在运行时会快速关闭。

我想知道当应用程序执行时,当它在任务栏中(在后台运行?)时,我的应用程序窗口状态如何恢复正常?

谢谢。

1 个答案:

答案 0 :(得分:0)

首先将此助手类添加到项目中。

Friend Class NativeMethods

    <DllImport("user32.dll", CharSet:=CharSet.Auto)> _
    Friend Shared Function PostMessage(ByVal hwnd As IntPtr, ByVal msg As Integer, ByVal wparam As IntPtr, ByVal lparam As IntPtr) As Boolean
    End Function

    <DllImport("user32.dll", CharSet:=CharSet.Auto)> _
    Friend Shared Function RegisterWindowMessage(ByVal msg As String) As Integer
    End Function

    Friend Const HWND_BROADCAST As Integer = &HFFFF
    Friend Shared ReadOnly WM_RESTORE As Integer = RegisterWindowMessage("WM_RESTORE")

End Class

然后,您需要为您的应用程序创建一个入口点。 (或者,如果你已经有一个,则进行修改)

Public Class Program

    Private Sub New()
    End Sub

    <STAThread()> _
    Friend Shared Sub Main()
        If (mutex.WaitOne(TimeSpan.Zero, True)) Then
            Application.EnableVisualStyles()
            Application.SetCompatibleTextRenderingDefault(False)
            Application.Run(New Form1()) '<- Replace this with an instance of your main form.
            Program.mutex.ReleaseMutex()
        Else
            NativeMethods.PostMessage(New IntPtr(NativeMethods.HWND_BROADCAST), NativeMethods.WM_RESTORE, IntPtr.Zero, IntPtr.Zero)
        End If
    End Sub

    Shared ReadOnly mutex As Mutex = New Mutex(True, "{A1CD1685-EFC9-4D63-BA66-CF2066857FC4}")

End Class

在您的主表单中添加以下代码。

Public Class Form1
    Inherits Form

    Private Sub Restore()
        Me.Show()
    End Sub

    Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
        If (m.Msg = NativeMethods.WM_RESTORE) Then
            Me.Restore()
        End If
        MyBase.WndProc(m)
    End Sub

End Class

最后,将应用程序启动对象更改为sub main。

How to: Change the Startup Object for an Application (Visual Basic)

<强>参考

http://sanity-free.org/143/csharp_dotnet_single_instance_application.html