2014-08-31 22 views
1

我正在寫一個應用程序,既應該運行winform模式或控制檯模式。問題是我不知道我的應用程序是如何啓動的。如果它使用控制檯啓動,它應該做一些工作人員,其他方面它應該顯示一個winform。如何知道應用程序是從控制檯還是資源管理器運行?

​​3210

提前乾杯:)!

+0

上面的鏈接是你該怎麼也不惡意實施它。也檢查這一個:http://stackoverflow.com/questions/1188658/how-can-ac-sharp-windows-console-application-tell-if-it-is-run-interactively – Neolisk 2014-08-31 17:09:12

回答

0

我找到了你需要的答案,但它是用C#編寫的。你可以簡單地使用C#來VB.net轉換器,如果你不知道C#,或將其轉換手動

從一個類似的問題。實測值:https://stackoverflow.com/a/3346055/1388267

​​3210

你可以得到父進程的句柄,然後檢查其名字就知道它是否是資源管理器或命令提示符

編輯:剛剛纔轉換成VB.net這樣你就可以直接使用它:

''' <summary> 
''' A utility class to determine a process parent. 
''' </summary> 
<StructLayout(LayoutKind.Sequential)> _ 
Public Structure ParentProcessUtilities 
    ' These members must match PROCESS_BASIC_INFORMATION 
    Friend Reserved1 As IntPtr 
    Friend PebBaseAddress As IntPtr 
    Friend Reserved2_0 As IntPtr 
    Friend Reserved2_1 As IntPtr 
    Friend UniqueProcessId As IntPtr 
    Friend InheritedFromUniqueProcessId As IntPtr 

    <DllImport("ntdll.dll")> _ 
    Private Shared Function NtQueryInformationProcess(processHandle As IntPtr, processInformationClass As Integer, ByRef processInformation As ParentProcessUtilities, processInformationLength As Integer, ByRef returnLength As Integer) As Integer 
    End Function 

    ''' <summary> 
    ''' Gets the parent process of the current process. 
    ''' </summary> 
    ''' <returns>An instance of the Process class.</returns> 
    Public Shared Function GetParentProcess() As Process 
     Return GetParentProcess(Process.GetCurrentProcess().Handle) 
    End Function 

    ''' <summary> 
    ''' Gets the parent process of specified process. 
    ''' </summary> 
    ''' <param name="id">The process id.</param> 
    ''' <returns>An instance of the Process class.</returns> 
    Public Shared Function GetParentProcess(id As Integer) As Process 
     Dim process__1 As Process = Process.GetProcessById(id) 
     Return GetParentProcess(process__1.Handle) 
    End Function 

    ''' <summary> 
    ''' Gets the parent process of a specified process. 
    ''' </summary> 
    ''' <param name="handle">The process handle.</param> 
    ''' <returns>An instance of the Process class.</returns> 
    Public Shared Function GetParentProcess(handle As IntPtr) As Process 
     Dim pbi As New ParentProcessUtilities() 
     Dim returnLength As Integer 
     Dim status As Integer = NtQueryInformationProcess(handle, 0, pbi, Marshal.SizeOf(pbi), returnLength) 
     If status <> 0 Then 
      Throw New Win32Exception(status) 
     End If 

     Try 
      Return Process.GetProcessById(pbi.InheritedFromUniqueProcessId.ToInt32()) 
     Catch generatedExceptionName As ArgumentException 
      ' not found 
      Return Nothing 
     End Try 
    End Function 
End Structure 
+0

我真的很討厭downvote爲沒有理由。只要告訴我你的評論在評論後你的問題是什麼。神! – 2014-08-31 20:08:36

相關問題