如何使用按钮隐藏/显示进程

问题描述:

我创建了测试应用程序并打开了一个进程,当我尝试通过单击隐藏按钮隐藏它时,我得到的消息:对象引用未设置为对象的实例。



我使用的代码:



I created test application and opened one process, when i trying to hide it by clicking hide button the message i get : Object reference not set to an instance of an object.

The code i use:

Imports System.Runtime.InteropServices

Public Class Form1

    Const SW_HIDE As Integer = 0
    Const SW_SHOW As Integer = 1

    Dim process As Process


    <DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
    Private Shared Function ShowWindow(ByVal hwnd As IntPtr, nCmdShow As Integer) As Boolean
    End Function


    'Button for Hide process
    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click

        ShowWindow(process.MainWindowHandle, SW_HIDE)

    End Sub

    'Button for Show process
    Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click

        ShowWindow(process.MainWindowHandle, SW_SHOW)

    End Sub

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load

        Dim psi As ProcessStartInfo = New ProcessStartInfo()

        psi.FileName = "Calc.exe"
        TextBox1.Text = "Start calculator"

        process.Start(psi)

        'Wait until the process has a main window handle.
        While process.MainWindowHandle = IntPtr.Zero
            process.Refresh()
        End While

    End Sub
End Class





当我按下隐藏按钮时出现错误消息

行:ShowWindow(process.MainWindowHandle,SW_HIDE)



谢谢。



The Error Message appears when i push Hide button
Line : ShowWindow(process.MainWindowHandle, SW_HIDE)

Thank you.

好的,试试这个:



而不是这一行:

Ok,try this:

Instead of this line:
process.Start(psi)





使用它:



Use this:

process.StartInfo = psi
process.Start()





编辑

查看MSDN后,我看到Process.Start(ProcessStartInfo)返回一个进程,所以这也可以工作:





EDIT
After looking at MSDN, I see that Process.Start(ProcessStartInfo) returns a process,so this would also work:

process = process.Start(psi)