使用Visual Basic在Windows窗体中嵌入DOS控制台

时间:2012-01-12 08:01:43

标签: .net windows vb.net winapi windows-console

我已经设法从其他问题中找到了一些允许我实现下一个代码的数据:

Imports System.Runtime.InteropServices

Public Class Form1

    <DllImport("user32.dll")> _
    Public Shared Function MoveWindow(ByVal hWnd As IntPtr, ByVal x As Integer, ByVal y As Integer, ByVal nWidth As Integer, ByVal nHeight As Integer, ByVal bRepaint As Boolean) As Boolean
    End Function

    <DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
    Public Shared Function SetParent(ByVal hWndChild As IntPtr, ByVal hWndNewParent As IntPtr) As IntPtr
    End Function

    <DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
    Private Shared Function FindWindow( _
     ByVal lpClassName As String, _
     ByVal lpWindowName As String) As IntPtr
    End Function

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim hwnd As IntPtr
        hwnd = FindWindow(vbNullChar, "C:\\WINDOWS\\system32\\cmd.exe")

        If hwnd.Equals(IntPtr.Zero) Then
            MessageBox.Show("Got null handle")
        Else
            SetParent(hwnd, Me.Handle)
            MoveWindow(hwnd, 0, 0, Me.Width, Me.Height, False)
        End If
    End Sub
End Class

我的问题是我无法找到DOS控制台窗口。

C#中的问题 Embedding a DOS console in a windows form

1 个答案:

答案 0 :(得分:1)

使用bring a console window to front in c#作为基础,您可以修改代码:

<DllImport("user32.dll", EntryPoint:="FindWindow", SetLastError:=True)> _
Private Shared Function FindWindowByCaption(ByVal zeroOnly As IntPtr, ByVal lpWindowName As String) As IntPtr
End Function

''in frmLoad:
hwnd = FindWindowByCaption(IntPtr.Zero, "c:\WINDOWS\system32\cmd.exe")

正如Jon Skeet所说:

  

这很糟糕,很可怕,但它对我有用(谢谢,pinvoke.net!):

Cody Gray对此也是正确的:

  

您可能无法找到它,因为它不会始终具有此标题:C:\\WINDOWS\\system32\\cmd.exe。例如,我没有。

所以它有效,但是很脆弱。