locked
Running a command on a cmd RRS feed

  • Question

  • Hello,

    I am trying to make a program that can run commands on an already opened cmd file

    Like i have found a lot of different command but when you run a command it opens a new cmd file with the command you wrote.

    What i mean:

    On your windows vb form you have 1 textbox and 2 buttons

    The first button opens the cmd file

    The second button sends the command you wrote on textbox in the already opened cmd file.

    how am i supposed to do that?

    I have found this code but it opens a different cmd when you run a command through the textbox:

    Shell("cmd.exe /k" + Textbox1.Text)


    Friday, July 8, 2016 4:52 PM

Answers

  • Hello,

    I am trying to make a program that can run commands on an already opened cmd file

    Like i have found a lot of different command but when you run a command it opens a new cmd file with the command you wrote.

    What i mean:

    On your windows vb form you have 1 textbox and 2 buttons

    The first button opens the cmd file

    The second button sends the command you wrote on textbox in the already opened cmd file.

    how am i supposed to do that?

    I have found this code but it opens a different cmd when you run a command through the textbox:

    Shell("cmd.exe /k" + Textbox1.Text)


    If you want the Cmd prompt visible and you want to constantly send commands to it and watch what it does then the below code will work. It gets the Console Window of the Cmd prompt and sends whatever characters are in the TextBox which then appear on the line of the Console Window. After all the characters in the TextBox are sent then an enter is sent so the Cmd prompt processes whatever was placed as a command for it to perform.

    Button1 launches a Cmd prompt, gets the Cmd prompts Console Window hWnd and then Button1 is disabled.

    After that Button2 can send TextBox1 characters to the Cmd prompts Console Window. The Cmd prompt then performs whatever the instructions are.

    Button3 is for killing the Cmd prompt and enabling Button1 again.

    Only 1 Cmd prompt can be running as the code for getting the Cmd prompts Console Window hWnd can not differentiate between different Cmd prompt Console Windows for which to use. Although the code could probably be altered to only get the Cmd prompts Console Window for the Cmd prompt launched using p.Start.

    Option Strict On
    
    Public Class Form1
    
        Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" _
            (ByVal hwnd As Int32, ByVal wMsg As Int32, ByVal wParam As Int32, ByVal lParam As Int32) As Int32
    
        Const WM_CHAR As UInt32 = &H102
    
        Dim p As New Process
        Dim h As Integer
    
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            Me.Location = New Point(0, 0)
        End Sub
    
        Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
            Try
                p.Kill() ' Stops the Cmd process immediately when Form1 exits.
            Catch ex As Exception
            End Try
        End Sub
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Dim PSI As New ProcessStartInfo
            PSI.FileName = "C:\Windows\system32\cmd.exe"
            PSI.UseShellExecute = True
            p.StartInfo = PSI
            p.Start()
            System.Threading.Thread.Sleep(3000)
            Dim enumerator As New WindowsEnumerator()
            For Each top As ApiWindow In enumerator.GetTopLevelWindows()
                If top.ClassName = "ConsoleWindowClass" Then
                    h = top.hWnd
                End If
            Next
            Button1.Enabled = False
        End Sub
    
        Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
            If TextBox1.Text <> "" Then
                For i = 0 To TextBox1.Text.Count - 1
                    SendMessage(h, WM_CHAR, AscW(TextBox1.Text(i)), 0) ' Sends each char in TextBox one at a time to Cmd Console Window.
                Next
                SendMessage(h, WM_CHAR, 13, 0) ' Sends enter to Cmd Console Window so Cmd executes the command from the TextBox.
            End If
        End Sub
    
        Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
            Try
                p.Kill() ' Stops the Cmd process immediately.
            Catch ex As Exception
            End Try
            Button1.Enabled = True
        End Sub
    
        Public Class ApiWindow
            Public MainWindowTitle As String = ""
            Public ClassName As String = ""
            Public hWnd As Int32
        End Class
    
        ''' <summary> 
        ''' Enumerate top-level and child windows 
        ''' </summary> 
        ''' <example> 
        ''' Dim enumerator As New WindowsEnumerator()
        ''' For Each top As ApiWindow in enumerator.GetTopLevelWindows()
        '''    Console.WriteLine(top.MainWindowTitle)
        '''    For Each child As ApiWindow child in enumerator.GetChildWindows(top.hWnd) 
        '''        Console.WriteLine(" " + child.MainWindowTitle)
        '''    Next child
        ''' Next top
        ''' </example> 
        Public Class WindowsEnumerator
    
            Private Delegate Function EnumCallBackDelegate(ByVal hwnd As Integer, ByVal lParam As Integer) As Integer
    
            ' Top-level windows.
            Private Declare Function EnumWindows Lib "user32" _
             (ByVal lpEnumFunc As EnumCallBackDelegate, ByVal lParam As Integer) As Integer
    
            ' Child windows.
            Private Declare Function EnumChildWindows Lib "user32" _
             (ByVal hWndParent As Integer, ByVal lpEnumFunc As EnumCallBackDelegate, ByVal lParam As Integer) As Integer
    
            ' Get the window class.
            Private Declare Function GetClassName _
             Lib "user32" Alias "GetClassNameA" _
             (ByVal hwnd As Integer, ByVal lpClassName As StringBuilder, ByVal nMaxCount As Integer) As Integer
    
            ' Test if the window is visible--only get visible ones.
            Private Declare Function IsWindowVisible Lib "user32" _
             (ByVal hwnd As Integer) As Integer
    
            ' Test if the window's parent--only get the one's without parents.
            Private Declare Function GetParent Lib "user32" _
             (ByVal hwnd As Integer) As Integer
    
            ' Get window text length signature.
            Private Declare Function SendMessage _
             Lib "user32" Alias "SendMessageA" _
             (ByVal hwnd As Int32, ByVal wMsg As Int32, ByVal wParam As Int32, ByVal lParam As Int32) As Int32
    
            ' Get window text signature.
            Private Declare Function SendMessage _
             Lib "user32" Alias "SendMessageA" _
             (ByVal hwnd As Int32, ByVal wMsg As Int32, ByVal wParam As Int32, ByVal lParam As StringBuilder) As Int32
    
            Private _listChildren As New List(Of ApiWindow)
            Private _listTopLevel As New List(Of ApiWindow)
    
            Private _topLevelClass As String = ""
            Private _childClass As String = ""
    
            ''' <summary>
            ''' Get all top-level window information
            ''' </summary>
            ''' <returns>List of window information objects</returns>
            Public Overloads Function GetTopLevelWindows() As List(Of ApiWindow)
    
                EnumWindows(AddressOf EnumWindowProc, &H0)
    
                Return _listTopLevel
    
            End Function
    
            Public Overloads Function GetTopLevelWindows(ByVal className As String) As List(Of ApiWindow)
    
                _topLevelClass = className
    
                Return Me.GetTopLevelWindows()
    
            End Function
    
            ''' <summary>
            ''' Get all child windows for the specific windows handle (hwnd).
            ''' </summary>
            ''' <returns>List of child windows for parent window</returns>
            Public Overloads Function GetChildWindows(ByVal hwnd As Int32) As List(Of ApiWindow)
    
                ' Clear the window list.
                _listChildren = New List(Of ApiWindow)
    
                ' Start the enumeration process.
                EnumChildWindows(hwnd, AddressOf EnumChildWindowProc, &H0)
    
                ' Return the children list when the process is completed.
                Return _listChildren
    
            End Function
    
            Public Overloads Function GetChildWindows(ByVal hwnd As Int32, ByVal childClass As String) As List(Of ApiWindow)
    
                ' Set the search
                _childClass = childClass
    
                Return Me.GetChildWindows(hwnd)
    
            End Function
    
            ''' <summary>
            ''' Callback function that does the work of enumerating top-level windows.
            ''' </summary>
            ''' <param name="hwnd">Discovered Window handle</param>
            ''' <returns>1=keep going, 0=stop</returns>
            Private Function EnumWindowProc(ByVal hwnd As Int32, ByVal lParam As Int32) As Int32
    
                ' Eliminate windows that are not top-level.
                If GetParent(hwnd) = 0 AndAlso CBool(IsWindowVisible(hwnd)) Then
    
                    ' Get the window title / class name.
                    Dim window As ApiWindow = GetWindowIdentification(hwnd)
    
                    ' Match the class name if searching for a specific window class.
                    If _topLevelClass.Length = 0 OrElse window.ClassName.ToLower() = _topLevelClass.ToLower() Then
                        _listTopLevel.Add(window)
                    End If
    
                End If
    
                ' To continue enumeration, return True (1), and to stop enumeration 
                ' return False (0).
                ' When 1 is returned, enumeration continues until there are no 
                ' more windows left.
    
                Return 1
    
            End Function
    
            ''' <summary>
            ''' Callback function that does the work of enumerating child windows.
            ''' </summary>
            ''' <param name="hwnd">Discovered Window handle</param>
            ''' <returns>1=keep going, 0=stop</returns>
            Private Function EnumChildWindowProc(ByVal hwnd As Int32, ByVal lParam As Int32) As Int32
    
                Dim window As ApiWindow = GetWindowIdentification(hwnd)
    
                ' Attempt to match the child class, if one was specified, otherwise
                ' enumerate all the child windows.
                If _childClass.Length = 0 OrElse window.ClassName.ToLower() = _childClass.ToLower() Then
                    _listChildren.Add(window)
                End If
    
                Return 1
    
            End Function
    
            ''' <summary>
            ''' Build the ApiWindow object to hold information about the Window object.
            ''' </summary>
            Private Function GetWindowIdentification(ByVal hwnd As Integer) As ApiWindow
    
                Const WM_GETTEXT As Int32 = &HD
                Const WM_GETTEXTLENGTH As Int32 = &HE
    
                Dim window As New ApiWindow()
    
                Dim title As New StringBuilder()
    
                ' Get the size of the string required to hold the window title.
                Dim size As Int32 = SendMessage(hwnd, WM_GETTEXTLENGTH, 0, 0)
    
                ' If the return is 0, there is no title.
                If size > 0 Then
                    title = New StringBuilder(size + 1)
    
                    SendMessage(hwnd, WM_GETTEXT, title.Capacity, title)
                End If
    
                ' Get the class name for the window.
                Dim classBuilder As New StringBuilder(64)
                GetClassName(hwnd, classBuilder, 64)
    
                ' Set the properties for the ApiWindow object.
                window.ClassName = classBuilder.ToString()
                window.MainWindowTitle = title.ToString()
                window.hWnd = hwnd
    
                Return window
    
            End Function
    
        End Class
    
    End Class

    Top two pics are app with Cmd prompt displayed. Bottom two pics are app displaying command "cd .." in TextBox1 and after Button2 was selected 5 or 6 times so you can see in the Cmd prompts Console Window the Cmd prompt performed the command some amount of times.


    La vida loca

    • Marked as answer by TheodosisXx Friday, July 8, 2016 9:21 PM
    Friday, July 8, 2016 7:25 PM
  • Same problem save-al not save-all

    I made a new form, i copy paste the code and put 1 textbox and on button on the form

    I want to the code and i set the path where my batch file is 

    Cmd = Process.Start("C:\Users\Theodosis\Desktop\Test\RunServer.bat", "/k")

    Pictures:

    Code:


    Form:

     When i open the batch file:


    When i type the save-all command:

    And here is the error:

    On the cmd it says that:

    >save-al

    >

    >Unknown command. Type "/help" for help



    Uh huh. This my last attempt unless the broken record "it does not work" with no other details of how to reproduce the problem changes.

    I cant read those images. Why don't you show the code in a code window so we can easily copy it? Why don't you explain what the problem is? You wrote:

    On the cmd it says that:

    >save-al

    >

    >Unknown command. Type "/help" for help

    Is that suppose to explain what the problem is such that we can reproduce it?

    It does not.

    If the explanation is in the images I cant see them. All I see is trash on the screen.

    I changed this example to enter the folder as you did in your code image and it still works as expected. Same batch. When you make the command as you did and put the /k in quotes like you did it gets echoed from the batch. See it in the image? Same batch file as last example.

    Since that is all you have given for us that is all I can do.

    Public Class Form5
        Private Cmd As Process = Nothing
        Private Const WM_CHAR As UInteger = &H102
    
        <Runtime.InteropServices.DllImport("user32.dll", EntryPoint:="SendMessageW")>
        Private Shared Function SendMessageW(ByVal hWnd As IntPtr, ByVal Msg As UInteger, ByVal wParam As UInteger, ByVal lParam As Integer) As Integer
        End Function
    
        Private Sub Form5_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            TextBox1.Enabled = False
        End Sub
    
        Private Sub TextBox1_KeyDown(sender As Object, e As KeyEventArgs) Handles TextBox1.KeyDown
            If e.KeyCode = Keys.Enter AndAlso TextBox1.Text.Trim <> "" AndAlso Cmd IsNot Nothing AndAlso Not Cmd.HasExited Then
                Dim command As String = TextBox1.Text & Chr(13) & Chr(13)
                For Each c As Char In command.ToCharArray
                    SendMessageW(Cmd.MainWindowHandle, WM_CHAR, CUInt(AscW(c)), 0)
                Next
    
                TextBox1.Clear()
            End If
        End Sub
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            If Cmd Is Nothing OrElse Cmd.HasExited Then
    
                'Cmd = Process.Start("cmd.exe", "/k cd\")
    
                Cmd = Process.Start("C:\test\batch1.bat", "/k cd\")
    
            End If
    
            TextBox1.Enabled = True
    
        End Sub
    End Class


    • Edited by tommytwotrain Sunday, July 10, 2016 12:51 PM new image
    • Marked as answer by TheodosisXx Sunday, July 10, 2016 12:57 PM
    Sunday, July 10, 2016 12:37 PM
  • Ok guys thanks for your help
    • Marked as answer by TheodosisXx Sunday, July 10, 2016 12:56 PM
    Sunday, July 10, 2016 12:56 PM

All replies

  • Theo,

    If I understand correctly you can use a StreamReader to read the file:

    Using rdr As New System.IO.StreamReader("filePathHere")
        Do While rdr.Peek() >= 0
            Dim itm As String = rdr.ReadLine.Trim
                'Now process the line “itm”
             Loop
    End Using
    

    Then you will modify it and to write it back, you could use a StreamWriter or several other ways, but if you just use File.WriteAllText and give it the .Text property of the TextBox, it will work - but do know that since the file exists, you'll need to delete it first.

    You can also just use My.Computer, FileSystem,WriteAllText and you'll get an option whether or not to append to the file (set it false and it will overwrite the file).


    In the middle of difficulty ... lies opportunity. -- Albert Einstein

    Friday, July 8, 2016 5:09 PM
  • Try this in a new project.  It's not exactly what you asked for but it comes quite close.

    Public Class Form1
       Private P As New Process
       Private SW As System.IO.StreamWriter
       Private WithEvents TB As New TextBox With {.Location = New Point(20, 20), .Multiline = True, .Dock = DockStyle.Fill}
       Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
          Controls.Add(TB)
          AddHandler P.OutputDataReceived, AddressOf DisplayOutput
          P.StartInfo.CreateNoWindow() = True
          P.StartInfo.UseShellExecute = False
          P.StartInfo.RedirectStandardInput = True
          P.StartInfo.RedirectStandardOutput = True
          P.StartInfo.RedirectStandardError = True
          P.StartInfo.FileName = "cmd.exe"
          P.Start()
          P.SynchronizingObject = TB
          P.BeginOutputReadLine()
          SW = P.StandardInput
          SW.WriteLine()
       End Sub
        Private Sub DisplayOutput(ByVal sendingProcess As Object, ByVal output As DataReceivedEventArgs)
          TB.AppendText(output.Data() & vbCrLf)
        End Sub
       Private Sub TB_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TB.KeyPress
          Static Line As String = ""
          If e.KeyChar = Chr(Keys.Return) Then
             If Line.Length > 0 Then
                SW.WriteLine(Line & vbCrLf)
                Line = ""
             End If
          Else
             Line = Line & e.KeyChar
          End If
       End Sub
    End Class
    

    Friday, July 8, 2016 5:11 PM
  • Dave,

    I must have misunderstood what he wanted - I thought he just wanted to modify the batch file and write it back to disk.

    Your understanding is that he wants to execute it though?


    In the middle of difficulty ... lies opportunity. -- Albert Einstein

    Friday, July 8, 2016 5:13 PM
  • Well one of us has misunderstood - I wouldn't put any money on who's got it right though :)
    Friday, July 8, 2016 5:16 PM
  • Well one of us has misunderstood - I wouldn't put any money on who's got it right though :)

    You're likely correct - now that I've reread it, he was showing using Shell so, yea that's what he wanted to do.

    Not my first or last at goof ups! ;-)


    In the middle of difficulty ... lies opportunity. -- Albert Einstein

    Friday, July 8, 2016 5:19 PM
  • Hello,

    I am trying to make a program that can run commands on an already opened cmd file

    Like i have found a lot of different command but when you run a command it opens a new cmd file with the command you wrote.

    What i mean:

    On your windows vb form you have 1 textbox and 2 buttons

    The first button opens the cmd file

    The second button sends the command you wrote on textbox in the already opened cmd file.

    how am i supposed to do that?

    I have found this code but it opens a different cmd when you run a command through the textbox:

    Shell("cmd.exe /k" + Textbox1.Text)


    If you want the Cmd prompt visible and you want to constantly send commands to it and watch what it does then the below code will work. It gets the Console Window of the Cmd prompt and sends whatever characters are in the TextBox which then appear on the line of the Console Window. After all the characters in the TextBox are sent then an enter is sent so the Cmd prompt processes whatever was placed as a command for it to perform.

    Button1 launches a Cmd prompt, gets the Cmd prompts Console Window hWnd and then Button1 is disabled.

    After that Button2 can send TextBox1 characters to the Cmd prompts Console Window. The Cmd prompt then performs whatever the instructions are.

    Button3 is for killing the Cmd prompt and enabling Button1 again.

    Only 1 Cmd prompt can be running as the code for getting the Cmd prompts Console Window hWnd can not differentiate between different Cmd prompt Console Windows for which to use. Although the code could probably be altered to only get the Cmd prompts Console Window for the Cmd prompt launched using p.Start.

    Option Strict On
    
    Public Class Form1
    
        Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" _
            (ByVal hwnd As Int32, ByVal wMsg As Int32, ByVal wParam As Int32, ByVal lParam As Int32) As Int32
    
        Const WM_CHAR As UInt32 = &H102
    
        Dim p As New Process
        Dim h As Integer
    
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            Me.Location = New Point(0, 0)
        End Sub
    
        Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
            Try
                p.Kill() ' Stops the Cmd process immediately when Form1 exits.
            Catch ex As Exception
            End Try
        End Sub
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Dim PSI As New ProcessStartInfo
            PSI.FileName = "C:\Windows\system32\cmd.exe"
            PSI.UseShellExecute = True
            p.StartInfo = PSI
            p.Start()
            System.Threading.Thread.Sleep(3000)
            Dim enumerator As New WindowsEnumerator()
            For Each top As ApiWindow In enumerator.GetTopLevelWindows()
                If top.ClassName = "ConsoleWindowClass" Then
                    h = top.hWnd
                End If
            Next
            Button1.Enabled = False
        End Sub
    
        Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
            If TextBox1.Text <> "" Then
                For i = 0 To TextBox1.Text.Count - 1
                    SendMessage(h, WM_CHAR, AscW(TextBox1.Text(i)), 0) ' Sends each char in TextBox one at a time to Cmd Console Window.
                Next
                SendMessage(h, WM_CHAR, 13, 0) ' Sends enter to Cmd Console Window so Cmd executes the command from the TextBox.
            End If
        End Sub
    
        Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
            Try
                p.Kill() ' Stops the Cmd process immediately.
            Catch ex As Exception
            End Try
            Button1.Enabled = True
        End Sub
    
        Public Class ApiWindow
            Public MainWindowTitle As String = ""
            Public ClassName As String = ""
            Public hWnd As Int32
        End Class
    
        ''' <summary> 
        ''' Enumerate top-level and child windows 
        ''' </summary> 
        ''' <example> 
        ''' Dim enumerator As New WindowsEnumerator()
        ''' For Each top As ApiWindow in enumerator.GetTopLevelWindows()
        '''    Console.WriteLine(top.MainWindowTitle)
        '''    For Each child As ApiWindow child in enumerator.GetChildWindows(top.hWnd) 
        '''        Console.WriteLine(" " + child.MainWindowTitle)
        '''    Next child
        ''' Next top
        ''' </example> 
        Public Class WindowsEnumerator
    
            Private Delegate Function EnumCallBackDelegate(ByVal hwnd As Integer, ByVal lParam As Integer) As Integer
    
            ' Top-level windows.
            Private Declare Function EnumWindows Lib "user32" _
             (ByVal lpEnumFunc As EnumCallBackDelegate, ByVal lParam As Integer) As Integer
    
            ' Child windows.
            Private Declare Function EnumChildWindows Lib "user32" _
             (ByVal hWndParent As Integer, ByVal lpEnumFunc As EnumCallBackDelegate, ByVal lParam As Integer) As Integer
    
            ' Get the window class.
            Private Declare Function GetClassName _
             Lib "user32" Alias "GetClassNameA" _
             (ByVal hwnd As Integer, ByVal lpClassName As StringBuilder, ByVal nMaxCount As Integer) As Integer
    
            ' Test if the window is visible--only get visible ones.
            Private Declare Function IsWindowVisible Lib "user32" _
             (ByVal hwnd As Integer) As Integer
    
            ' Test if the window's parent--only get the one's without parents.
            Private Declare Function GetParent Lib "user32" _
             (ByVal hwnd As Integer) As Integer
    
            ' Get window text length signature.
            Private Declare Function SendMessage _
             Lib "user32" Alias "SendMessageA" _
             (ByVal hwnd As Int32, ByVal wMsg As Int32, ByVal wParam As Int32, ByVal lParam As Int32) As Int32
    
            ' Get window text signature.
            Private Declare Function SendMessage _
             Lib "user32" Alias "SendMessageA" _
             (ByVal hwnd As Int32, ByVal wMsg As Int32, ByVal wParam As Int32, ByVal lParam As StringBuilder) As Int32
    
            Private _listChildren As New List(Of ApiWindow)
            Private _listTopLevel As New List(Of ApiWindow)
    
            Private _topLevelClass As String = ""
            Private _childClass As String = ""
    
            ''' <summary>
            ''' Get all top-level window information
            ''' </summary>
            ''' <returns>List of window information objects</returns>
            Public Overloads Function GetTopLevelWindows() As List(Of ApiWindow)
    
                EnumWindows(AddressOf EnumWindowProc, &H0)
    
                Return _listTopLevel
    
            End Function
    
            Public Overloads Function GetTopLevelWindows(ByVal className As String) As List(Of ApiWindow)
    
                _topLevelClass = className
    
                Return Me.GetTopLevelWindows()
    
            End Function
    
            ''' <summary>
            ''' Get all child windows for the specific windows handle (hwnd).
            ''' </summary>
            ''' <returns>List of child windows for parent window</returns>
            Public Overloads Function GetChildWindows(ByVal hwnd As Int32) As List(Of ApiWindow)
    
                ' Clear the window list.
                _listChildren = New List(Of ApiWindow)
    
                ' Start the enumeration process.
                EnumChildWindows(hwnd, AddressOf EnumChildWindowProc, &H0)
    
                ' Return the children list when the process is completed.
                Return _listChildren
    
            End Function
    
            Public Overloads Function GetChildWindows(ByVal hwnd As Int32, ByVal childClass As String) As List(Of ApiWindow)
    
                ' Set the search
                _childClass = childClass
    
                Return Me.GetChildWindows(hwnd)
    
            End Function
    
            ''' <summary>
            ''' Callback function that does the work of enumerating top-level windows.
            ''' </summary>
            ''' <param name="hwnd">Discovered Window handle</param>
            ''' <returns>1=keep going, 0=stop</returns>
            Private Function EnumWindowProc(ByVal hwnd As Int32, ByVal lParam As Int32) As Int32
    
                ' Eliminate windows that are not top-level.
                If GetParent(hwnd) = 0 AndAlso CBool(IsWindowVisible(hwnd)) Then
    
                    ' Get the window title / class name.
                    Dim window As ApiWindow = GetWindowIdentification(hwnd)
    
                    ' Match the class name if searching for a specific window class.
                    If _topLevelClass.Length = 0 OrElse window.ClassName.ToLower() = _topLevelClass.ToLower() Then
                        _listTopLevel.Add(window)
                    End If
    
                End If
    
                ' To continue enumeration, return True (1), and to stop enumeration 
                ' return False (0).
                ' When 1 is returned, enumeration continues until there are no 
                ' more windows left.
    
                Return 1
    
            End Function
    
            ''' <summary>
            ''' Callback function that does the work of enumerating child windows.
            ''' </summary>
            ''' <param name="hwnd">Discovered Window handle</param>
            ''' <returns>1=keep going, 0=stop</returns>
            Private Function EnumChildWindowProc(ByVal hwnd As Int32, ByVal lParam As Int32) As Int32
    
                Dim window As ApiWindow = GetWindowIdentification(hwnd)
    
                ' Attempt to match the child class, if one was specified, otherwise
                ' enumerate all the child windows.
                If _childClass.Length = 0 OrElse window.ClassName.ToLower() = _childClass.ToLower() Then
                    _listChildren.Add(window)
                End If
    
                Return 1
    
            End Function
    
            ''' <summary>
            ''' Build the ApiWindow object to hold information about the Window object.
            ''' </summary>
            Private Function GetWindowIdentification(ByVal hwnd As Integer) As ApiWindow
    
                Const WM_GETTEXT As Int32 = &HD
                Const WM_GETTEXTLENGTH As Int32 = &HE
    
                Dim window As New ApiWindow()
    
                Dim title As New StringBuilder()
    
                ' Get the size of the string required to hold the window title.
                Dim size As Int32 = SendMessage(hwnd, WM_GETTEXTLENGTH, 0, 0)
    
                ' If the return is 0, there is no title.
                If size > 0 Then
                    title = New StringBuilder(size + 1)
    
                    SendMessage(hwnd, WM_GETTEXT, title.Capacity, title)
                End If
    
                ' Get the class name for the window.
                Dim classBuilder As New StringBuilder(64)
                GetClassName(hwnd, classBuilder, 64)
    
                ' Set the properties for the ApiWindow object.
                window.ClassName = classBuilder.ToString()
                window.MainWindowTitle = title.ToString()
                window.hWnd = hwnd
    
                Return window
    
            End Function
    
        End Class
    
    End Class

    Top two pics are app with Cmd prompt displayed. Bottom two pics are app displaying command "cd .." in TextBox1 and after Button2 was selected 5 or 6 times so you can see in the Cmd prompts Console Window the Cmd prompt performed the command some amount of times.


    La vida loca

    • Marked as answer by TheodosisXx Friday, July 8, 2016 9:21 PM
    Friday, July 8, 2016 7:25 PM
  • Thank you so much
    Saturday, July 9, 2016 8:21 AM
  • One more thing,

    When i am going to run a command with two same letters like this:

    Save-all

    On the cmd it shows me:

    Save-al

    How am i supposed to write on textbox Save-all and on cmd

    to take the command as Save-all and not as Save-al?





    • Edited by TheodosisXx Saturday, July 9, 2016 11:13 AM
    Saturday, July 9, 2016 11:12 AM
  •  I am not sure why you are only getting "save-al" instead of "save-all" but,  here is a much shorter version of what Mr. Monkeboy posted.  It seems to send all the characters without cutting off the last character.  You also do not need to enumerate through all the windows to get the cmd window handle since you can get it from the Process`s MainWindowHandle.

    This does not use a button to send the command,  you simply type your full command and press enter to send it.

     Test it out in a new Form project. Add 1 TextBox and 1 Button to the form.  Set the TextBox`s  Multiline property to True and its WordWrap property to False.  Then use this code.

    Public Class Form1
        Private Cmd As Process = Nothing
        Private Const WM_CHAR As UInteger = &H102

        <Runtime.InteropServices.DllImport("user32.dll", EntryPoint:="SendMessageW")>
        Private Shared Function SendMessageW(ByVal hWnd As IntPtr, ByVal Msg As UInteger, ByVal wParam As UInteger, ByVal lParam As Integer) As Integer
        End Function

        Private Sub Button_OpenCmd_Click(sender As Object, e As EventArgs) Handles Button_OpenCmd.Click
            If Cmd Is Nothing OrElse Cmd.HasExited Then
                Cmd = Process.Start("cmd.exe", "/k cd\ & cls") 'i added commands here to change the directory to C:\ and clear the cmd window when it opens
            End If
        End Sub

        Private Sub TextBox1_KeyDown(sender As Object, e As KeyEventArgs) Handles TextBox1.KeyDown
            If e.KeyCode = Keys.Enter AndAlso TextBox1.Text.Trim <> "" AndAlso Cmd IsNot Nothing AndAlso Not Cmd.HasExited Then
                e.Handled = True
                Dim command As String = TextBox1.Text & Chr(13)
                For Each c As Char In command.ToCharArray
                    SendMessageW(Cmd.MainWindowHandle, WM_CHAR, CUInt(AscW(c)), 0)
                Next
                TextBox1.Clear()
            End If
        End Sub
    End Class




    If you say it can`t be done then i`ll try it

    • Edited by IronRazerz Saturday, July 9, 2016 12:50 PM fixed bug
    • Proposed as answer by Mr. Monkeyboy Saturday, July 9, 2016 3:44 PM
    Saturday, July 9, 2016 12:37 PM
  •  If you want to use a button to send the commands then try this,  it seems to work better than using the KeyDown event in my opinion.

    Public Class Form1
        Private Cmd As Process = Nothing
        Private Const WM_CHAR As UInteger = &H102
    
        <Runtime.InteropServices.DllImport("user32.dll", EntryPoint:="SendMessageW")>
        Private Shared Function SendMessageW(ByVal hWnd As IntPtr, ByVal Msg As UInteger, ByVal wParam As UInteger, ByVal lParam As Integer) As Integer
        End Function
    
        Private Sub Button_OpenCmd_Click(sender As Object, e As EventArgs) Handles Button_OpenCmd.Click
            If Cmd Is Nothing OrElse Cmd.HasExited Then
                Cmd = Process.Start("cmd.exe", "/k cd\ & cls") 'i added commands here to change the directory to C:\ and clear the cmd window when it opens
            End If
        End Sub
    
        Private Sub Button_SendCommand_Click(sender As Object, e As EventArgs) Handles Button_SendCommand.Click
            If TextBox1.Text.Trim <> "" AndAlso Cmd IsNot Nothing AndAlso Not Cmd.HasExited Then
                Dim command As String = TextBox1.Text & Chr(13)
                For Each c As Char In command.ToCharArray
                    SendMessageW(Cmd.MainWindowHandle, WM_CHAR, CUInt(AscW(c)), 0)
                Next
                TextBox1.Clear()
            End If
        End Sub
    End Class


    If you say it can`t be done then i`ll try it

    • Edited by IronRazerz Saturday, July 9, 2016 5:09 PM
    Saturday, July 9, 2016 12:47 PM
  • It happens the same thing again.

    :/

    BTW thanks for your help

    I am running the commands on batch file not on cmd

    When i am trying to run the save-all command on cmd it works but

    the program that i am making is based on batch file and when i am trying to run save-all command

    again it shows me save-al.

    Maybe i must write a specific command on batch file?

    Batch file commands(i don't think this can help you :/)

    Echo Server Started
    Echo Thank you for using MinecraftServerMaker
    SET mypath=%~dp0
    echo %mypath:~0,-1%
    cd %mypath:~0,-1%
    java -Xmx1024M -Xms1024M -jar Server.jar nogui
    Pause
    And also thanks to everyone who helps me and still helping me :)


    Saturday, July 9, 2016 1:03 PM
  • It happens the same thing again.

    :/

    BTW thanks for your help

    I am running the commands on batch file not on cmd

    When i am trying to run the save-all command on cmd it works but

    the program that i am making is based on batch file and when i am trying to run save-all command

    again it shows me save-al.

    Maybe i must write a specific command on batch file?

    Batch file commands(i don't think this can help you :/)

    Echo Server Started
    Echo Thank you for using MinecraftServerMaker
    SET mypath=%~dp0
    echo %mypath:~0,-1%
    cd %mypath:~0,-1%
    java -Xmx1024M -Xms1024M -jar Server.jar nogui
    Pause
    And also thanks to everyone who helps me and still helping me :)


     Well, that definitely sounds like a problem caused by whatever you are doing in your batch file.  I don`t have any idea what that problem is.  Of coarse it may be because you have left out a lot of important details of how your application actually works too.

     

    If you say it can`t be done then i`ll try it

    Saturday, July 9, 2016 3:31 PM
  • It happens the same thing again.

    :/

    BTW thanks for your help

    I am running the commands on batch file not on cmd

    When i am trying to run the save-all command on cmd it works but

    the program that i am making is based on batch file and when i am trying to run save-all command

    again it shows me save-al.

    Maybe i must write a specific command on batch file?

    Batch file commands(i don't think this can help you :/)

    Echo Server Started
    Echo Thank you for using MinecraftServerMaker
    SET mypath=%~dp0
    echo %mypath:~0,-1%
    cd %mypath:~0,-1%
    java -Xmx1024M -Xms1024M -jar Server.jar nogui
    Pause
    And also thanks to everyone who helps me and still helping me :)


     Well, that definitely sounds like a problem caused by whatever you are doing in your batch file.  I don`t have any idea what that problem is.  Of coarse it may be because you have left out a lot of important details of how your application actually works too.

     

    If you say it can`t be done then i`ll try it

    Long shot: is something not the right carriage return or linefeed ie there is vblf and vbcr. Seems we sometimes had to use to two chr$(13)s or add another chr() I cant remember ie

    Dim command As String = TextBox1.Text & Chr(13) & chr (13)


    PS try using all three combinations of vblf and vbcr ie just vblf instead of chr(13), and just vbcr and try vblf & vbcr instead of chr(13) only.

    Saturday, July 9, 2016 3:35 PM
  • Long shot: is something not the right carriage return or linefeed ie there is vblf and vbcr. Seems we sometimes had to use to two chr$(13)s or add another chr() I cant remember ie

    Dim command As String = TextBox1.Text & Chr(13) & chr (13)


      It seems to work fine on my end when sending cmd commands to a cmd window,  batch file or no batch file.  I think it most likely has to do with something OP is doing in the code or the batch file since it appears to actually be running some java app.

    If you say it can`t be done then i`ll try it

    Saturday, July 9, 2016 3:59 PM
  • It happens the same thing again.

    :/

    BTW thanks for your help

    I am running the commands on batch file not on cmd

    When i am trying to run the save-all command on cmd it works but

    the program that i am making is based on batch file and when i am trying to run save-all command

    again it shows me save-al.

    Maybe i must write a specific command on batch file?

    Batch file commands(i don't think this can help you :/)

    Echo Server Started
    Echo Thank you for using MinecraftServerMaker
    SET mypath=%~dp0
    echo %mypath:~0,-1%
    cd %mypath:~0,-1%
    java -Xmx1024M -Xms1024M -jar Server.jar nogui
    Pause
    And also thanks to everyone who helps me and still helping me :)


     Well, that definitely sounds like a problem caused by whatever you are doing in your batch file.  I don`t have any idea what that problem is.  Of coarse it may be because you have left out a lot of important details of how your application actually works too.

     

    If you say it can`t be done then i`ll try it

    Long shot: is something not the right carriage return or linefeed ie there is vblf and vbcr. Seems we sometimes had to use to two chr$(13)s or add another chr() I cant remember ie

    Dim command As String = TextBox1.Text & Chr(13) & chr (13)


    PS try using all three combinations of vblf and vbcr ie just vblf instead of chr(13), and just vbcr and try vblf & vbcr instead of chr(13) only.

    I tested the Cmd prompt with 10 (LF line feed, NL new line) and 13 (CR carriage return) but only 13 worked.

    Ascii Table


    La vida loca

    Saturday, July 9, 2016 4:26 PM
  • I tested the Cmd prompt with 10 (LF line feed, NL new line) and 13 (CR carriage return) but only 13 worked.

    Ascii Table


    La vida loca

    Did you try vblf & vbcr both added together? Just to be sure. And use the vblf not the chr as I think this is why they made them? Are there chrw and etc? Again I don't remember the details maybe you do.

    PS also vblf & vblf.
    Saturday, July 9, 2016 5:10 PM
  • Long shot: is something not the right carriage return or linefeed ie there is vblf and vbcr. Seems we sometimes had to use to two chr$(13)s or add another chr() I cant remember ie

    Dim command As String = TextBox1.Text & Chr(13) & chr (13)


      It seems to work fine on my end when sending cmd commands to a cmd window,  batch file or no batch file.  I think it most likely has to do with something OP is doing in the code or the batch file since it appears to actually be running some java app.

    If you say it can`t be done then i`ll try it

    Ok. Well I am just recalling the old days and seems this is exactly the kind of thing where the end returns would become a problem. But I really don't remember. I hit it the other day and had to use both vblf & vbcr to get a new line in a rtb I think it was and the rest is just old memories.

    Saturday, July 9, 2016 5:15 PM
  • PS try using all three combinations of vblf and vbcr ie just vblf instead of chr(13), and just vbcr and try vblf & vbcr instead of chr(13) only.

     Dang it you!!!  You edited that in while i was posting.  8)

     I did actually try sending VbCr "chr(13)" and VbLf  "chr(10)" by mistake when testing it before posting it.  It responded as if you pressed enter twice in the cmd window.  Just the VbCr  "Chr(13)" is all that is needed.


    If you say it can`t be done then i`ll try it

    • Edited by IronRazerz Saturday, July 9, 2016 5:22 PM
    Saturday, July 9, 2016 5:20 PM
  • So where i must put this change ?
    Saturday, July 9, 2016 5:53 PM
  • So where i must put this change ?

    I was hoping you would know. I will let Razerz say.

    I just recall passing something to something and one had an end return of something but the other wanted something else.

    As I recall it can even happen passing a string, or a piece of data and etc.

    Since something is losing a character something else must be reading it first?

    But Razerz and Monkey know more about it I just said it was a long shot.

    Saturday, July 9, 2016 5:58 PM
  • So where i must put this change ?

    I was hoping you would know. I will let Razerz say.

    I just recall passing something to something and one had an end return of something but the other wanted something else.

    As I recall it can even happen passing a string, or a piece of data and etc.

    Since something is losing a character something else must be reading it first?

    But Razerz and Monkey know more about it I just said it was a long shot.

    PS and I mean from one program to another across the system. Not just in one vb project.

    Like the variable declarations are slight off by a half bit or something.

    But maybe I am way off.


    PS like one app was C++ and the other was VB.
    Saturday, July 9, 2016 5:59 PM
  • Ok thanks i will wait IronRazerz or Mr. Monkeyboy
    Saturday, July 9, 2016 6:05 PM
  • Ok thanks i will wait IronRazerz or Mr. Monkeyboy

    Well, if I understood Razerz what I am talking about is not the problem so you don't need to do anything with that.

    Its something else.

    PS So just ignore the comment I made about end returns. Razerz said this I think this is where we are:

    "It seems to work fine on my end when sending cmd commands to a cmd window,  batch file or no batch file.  I think it most likely has to do with something OP is doing in the code or the batch file since it appears to actually be running some java app."

    Saturday, July 9, 2016 6:09 PM
  • Ok thanks
    Saturday, July 9, 2016 6:39 PM
  • Ok thanks

    So, I guess we are awaiting something from you like more details of exactly what the problem is or a reproducible example of the question?

    It is still not clear to me exactly what you really want to do and what you want to do it with. I guess you were running the code examples and getting the same problem so something on your end is different than Razerz and Monkey what is it?

    Sorry if I side tracked things.


    Razer wrote:

    "Well, that definitely sounds like a problem caused by whatever you are doing in your batch file.  I don`t have any idea what that problem is.  Of coarse it may be because you have left out a lot of important details of how your application actually works too."

    Saturday, July 9, 2016 7:01 PM
  •  If you can show use the code you are using or as Tom mentioned,  a small example that reflects what your code does and will reproduce the same problem,  it would be a lot easier than us just guessing what is happening.

     Also if you can explain,  are you running the batch file from this application by sending a command?

     Are you trying to send more commands to the cmd window while the batch file is running?

     Is there a reason you need to run a batch file to start the jar file instead of just starting the jar file itself with the Process class?

     


    If you say it can`t be done then i`ll try it

    Saturday, July 9, 2016 7:22 PM
  • Code:

     Private Sub Button10_Click(sender As Object, e As EventArgs) Handles Button10.Click
            TextBox6.Text = ""
                   TextBox6.Text = "Save-all"
            If TextBox6.Text <> "" Then
                For i = 0 To TextBox6.Text.Count - 1
                    SendMessage(h, WM_CHAR, AscW(TextBox6.Text(i)), 0) ' Sends each char in TextBox one at a time to Cmd Console Window.
                Next
                SendMessage(h, WM_CHAR, 13, 0) ' Sends enter to Cmd Console Window so Cmd executes the command from the TextBox.
                TextBox6.Text = ""
            End If
        End Sub
    

    This is the command show let me explain:

    First i am cleaning the textbox that i am running the command to batch file

    So next i set the textbox to write the command save-all

    And then its your command for the cmd

    The problem is that when i am running the batch file it takes this code as save-al on as save-all (with double 'l').

    Also this batch file:

    Echo Server Started
    Echo Thank you for using MinecraftServerMaker
    SET mypath=%~dp0
    echo %mypath:~0,-1%
    cd %mypath:~0,-1%
    java -Xmx1024M -Xms1024M -jar Server.jar nogui
    Pause

    It starts a jave that must be ran through cmd and it sets the ram that can used on cmd because this

    java file is a minecraft server

    So you can set any amount of ram you want

    Thats all the explaination that i can give you.

    Saturday, July 9, 2016 8:05 PM
  •  It appears you are not using my code.  However,  that code modified to use the correct vb.net signature as shown in my example seems to write the whole string to the cmd window fine.  So,  it must be your batch file running the java app that is screwing it up somehow.

     Perhaps you can try removing the "Pause" from the end of your batch file.  It should not be needed if you are using the  /k  argument in the way i showed in my example.  The  /k  tells the cmd window to stay opened so,  Pause is not needed.

     

     I think you are going to need to just let the user type whatever they need to type into the cmd window.


    If you say it can`t be done then i`ll try it

    • Edited by IronRazerz Saturday, July 9, 2016 8:29 PM
    Saturday, July 9, 2016 8:25 PM
  • If i remove pause, the batch file will run the jar file and then will close

    Saturday, July 9, 2016 9:32 PM
  • If i remove pause, the batch file will run the jar file and then will close

     The "Pause" command should only be keeping the cmd window open after your jar file has been run.  If you try my example you will see that the /k argument will keep the cmd window open without the "Pause" being in the batch file.

     
    Public Class Form1
        Private Cmd As Process = Nothing
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            If Cmd Is Nothing OrElse Cmd.HasExited Then
                Cmd = Process.Start("cmd.exe", "/k C:\TestFolder\MyBatch.bat") 'the /k argument will keep the cmd window open after running my batch file
            End If
        End Sub
    End Class
     

     Here is the code for my batch file.

    @Echo Off
    cls
    cd\
    notepad C:\testfolder\LzwData.txt
    Echo Notice the cmd window does not close even without Pause in the batch file.
    

     


    If you say it can`t be done then i`ll try it


    • Edited by IronRazerz Saturday, July 9, 2016 10:33 PM
    Saturday, July 9, 2016 10:32 PM
  • IronRazerz,

    I tried and your code.

    It doesn't sends the code to the cmd

    Here is the code:

    Public Class Form5
    
        Private Cmd As Process = Nothing
        Private Const WM_CHAR As UInteger = &H102
    
        <Runtime.InteropServices.DllImport("user32.dll", EntryPoint:="SendMessageW")>
        Private Shared Function SendMessageW(ByVal hWnd As IntPtr, ByVal Msg As UInteger, ByVal wParam As UInteger, ByVal lParam As Integer) As Integer
        End Function
    
        Private Sub Button_OpenCmd_Click(sender As Object, e As EventArgs) Handles Button3.Click
            If Cmd Is Nothing OrElse Cmd.HasExited Then
                Cmd = Process.Start(TextBox1.Text & "/RunServer.bat", "/k & cls") 'i added commands here to change the directory to C:\ and clear the cmd window when it opens
            End If
        End Sub
    
        Private Sub TextBox6_KeyDown(sender As Object, e As KeyEventArgs) Handles TextBox6.KeyDown
            If e.KeyCode = Keys.Enter AndAlso TextBox1.Text.Trim <> "" AndAlso Cmd IsNot Nothing AndAlso Not Cmd.HasExited Then
                e.Handled = True
                Dim command As String = TextBox6.Text & Chr(13) & Chr(13)
                For Each c As Char In command.ToCharArray
                    SendMessageW(Cmd.MainWindowHandle, WM_CHAR, CUInt(AscW(c)), 0)
                Next
                TextBox6.Clear()
            End If
          End Sub
    
     Private Sub Button10_Click(sender As Object, e As EventArgs) Handles Button10.Click
            TextBox6.Text = ""
            TextBox6.Text = "Save-all"
        End Sub
    End class

    What else i must put on the code so the command on the textbox to send on the cmd?

    Sorry for asking this but i don't understand so good your code and i believe it doesn't works because

    of the textbox1_keydown

    If with some way you can turn the code to textbox1_textchanged i beleive it would work :)


    Sunday, July 10, 2016 7:50 AM
  • The line below looks like the problem to me.  What is in TextBox1? 

    Cmd = Process.Start(TextBox1.Text & "/RunServer.bat", "/k & cls")

     If that line of code is not starting "Cmd.exe" as i have shown in my example,  then the Process is not the Cmd window,  it would be whatever the program is in TextBox1.  That would be why it does not send the keys to the Cmd window.

     

    If you say it can`t be done then i`ll try it

    Sunday, July 10, 2016 10:28 AM
  • IronRazerz,

    I tried and your code.

    It doesn't sends the code to the cmd

    Here is the code:

    Public Class Form5
    
        Private Cmd As Process = Nothing
        Private Const WM_CHAR As UInteger = &H102
    
        <Runtime.InteropServices.DllImport("user32.dll", EntryPoint:="SendMessageW")>
        Private Shared Function SendMessageW(ByVal hWnd As IntPtr, ByVal Msg As UInteger, ByVal wParam As UInteger, ByVal lParam As Integer) As Integer
        End Function
    
        Private Sub Button_OpenCmd_Click(sender As Object, e As EventArgs) Handles Button3.Click
            If Cmd Is Nothing OrElse Cmd.HasExited Then
                Cmd = Process.Start(TextBox1.Text & "/RunServer.bat", "/k & cls") 'i added commands here to change the directory to C:\ and clear the cmd window when it opens
            End If
        End Sub
    
        Private Sub TextBox6_KeyDown(sender As Object, e As KeyEventArgs) Handles TextBox6.KeyDown
            If e.KeyCode = Keys.Enter AndAlso TextBox1.Text.Trim <> "" AndAlso Cmd IsNot Nothing AndAlso Not Cmd.HasExited Then
                e.Handled = True
                Dim command As String = TextBox6.Text & Chr(13) & Chr(13)
                For Each c As Char In command.ToCharArray
                    SendMessageW(Cmd.MainWindowHandle, WM_CHAR, CUInt(AscW(c)), 0)
                Next
                TextBox6.Clear()
            End If
          End Sub
    
     Private Sub Button10_Click(sender As Object, e As EventArgs) Handles Button10.Click
            TextBox6.Text = ""
            TextBox6.Text = "Save-all"
        End Sub
    End class

    What else i must put on the code so the command on the textbox to send on the cmd?

    Sorry for asking this but i don't understand so good your code and i believe it doesn't works because

    of the textbox1_keydown

    If with some way you can turn the code to textbox1_textchanged i beleive it would work :)


    I don't seem to have a problem with Razerz code?

    However, one does have to open the command window before you can send to it, are you doing that?

    Again you will have to describe somehow EXACTLY what the problem is on your end. If we cant reproduce it then there is not much to say.

    PS I updated the example to pass a variable to the batch file and show it when the batch runs. See where I added "Hello All" to the command? Seems to work ok.

    Public Class Form5
        Private Cmd As Process = Nothing
        Private Const WM_CHAR As UInteger = &H102
    
        <Runtime.InteropServices.DllImport("user32.dll", EntryPoint:="SendMessageW")>
        Private Shared Function SendMessageW(ByVal hWnd As IntPtr, ByVal Msg As UInteger, ByVal wParam As UInteger, ByVal lParam As Integer) As Integer
        End Function
    
        Private Sub Form5_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            TextBox1.Enabled = False
        End Sub
    
        Private Sub TextBox1_KeyDown(sender As Object, e As KeyEventArgs) Handles TextBox1.KeyDown
            If e.KeyCode = Keys.Enter AndAlso TextBox1.Text.Trim <> "" AndAlso Cmd IsNot Nothing AndAlso Not Cmd.HasExited Then
                Dim command As String = TextBox1.Text & Chr(13) & Chr(13)
                For Each c As Char In command.ToCharArray
                    SendMessageW(Cmd.MainWindowHandle, WM_CHAR, CUInt(AscW(c)), 0)
                Next
    
                TextBox1.Clear()
            End If
        End Sub
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            If Cmd Is Nothing OrElse Cmd.HasExited Then
                Cmd = Process.Start("cmd.exe", "/k cd\")
            End If
    
            TextBox1.Enabled = True
    
        End Sub
    End Class

    Here is the batch file

    echo off
    set arg1=%1
    set arg2=%2
    echo the command is %arg1% %arg2% 
    cd\
    notepad C:\test\testweather1.txt
    
    Echo Notice the cmd window does not close even without Pause in the batch file.
    
    




    • Edited by tommytwotrain Sunday, July 10, 2016 11:26 AM add hello all
    Sunday, July 10, 2016 10:31 AM
  • Same problem save-al not save-all

    I made a new form, i copy paste the code and put 1 textbox and on button on the form

    I want to the code and i set the path where my batch file is 

    Cmd = Process.Start("C:\Users\Theodosis\Desktop\Test\RunServer.bat", "/k")

    Pictures:

    Code:


    Form:

     When i open the batch file:


    When i type the save-all command:

    And here is the error:

    On the cmd it says that:

    >save-al

    >

    >Unknown command. Type "/help" for help



    Sunday, July 10, 2016 12:01 PM
  • Same problem save-al not save-all

    I made a new form, i copy paste the code and put 1 textbox and on button on the form

    I want to the code and i set the path where my batch file is 

    Cmd = Process.Start("C:\Users\Theodosis\Desktop\Test\RunServer.bat", "/k")

    Pictures:

    Code:


    Form:

     When i open the batch file:


    When i type the save-all command:

    And here is the error:

    On the cmd it says that:

    >save-al

    >

    >Unknown command. Type "/help" for help



    Uh huh. This my last attempt unless the broken record "it does not work" with no other details of how to reproduce the problem changes.

    I cant read those images. Why don't you show the code in a code window so we can easily copy it? Why don't you explain what the problem is? You wrote:

    On the cmd it says that:

    >save-al

    >

    >Unknown command. Type "/help" for help

    Is that suppose to explain what the problem is such that we can reproduce it?

    It does not.

    If the explanation is in the images I cant see them. All I see is trash on the screen.

    I changed this example to enter the folder as you did in your code image and it still works as expected. Same batch. When you make the command as you did and put the /k in quotes like you did it gets echoed from the batch. See it in the image? Same batch file as last example.

    Since that is all you have given for us that is all I can do.

    Public Class Form5
        Private Cmd As Process = Nothing
        Private Const WM_CHAR As UInteger = &H102
    
        <Runtime.InteropServices.DllImport("user32.dll", EntryPoint:="SendMessageW")>
        Private Shared Function SendMessageW(ByVal hWnd As IntPtr, ByVal Msg As UInteger, ByVal wParam As UInteger, ByVal lParam As Integer) As Integer
        End Function
    
        Private Sub Form5_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            TextBox1.Enabled = False
        End Sub
    
        Private Sub TextBox1_KeyDown(sender As Object, e As KeyEventArgs) Handles TextBox1.KeyDown
            If e.KeyCode = Keys.Enter AndAlso TextBox1.Text.Trim <> "" AndAlso Cmd IsNot Nothing AndAlso Not Cmd.HasExited Then
                Dim command As String = TextBox1.Text & Chr(13) & Chr(13)
                For Each c As Char In command.ToCharArray
                    SendMessageW(Cmd.MainWindowHandle, WM_CHAR, CUInt(AscW(c)), 0)
                Next
    
                TextBox1.Clear()
            End If
        End Sub
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            If Cmd Is Nothing OrElse Cmd.HasExited Then
    
                'Cmd = Process.Start("cmd.exe", "/k cd\")
    
                Cmd = Process.Start("C:\test\batch1.bat", "/k cd\")
    
            End If
    
            TextBox1.Enabled = True
    
        End Sub
    End Class


    • Edited by tommytwotrain Sunday, July 10, 2016 12:51 PM new image
    • Marked as answer by TheodosisXx Sunday, July 10, 2016 12:57 PM
    Sunday, July 10, 2016 12:37 PM
  • Ok guys thanks for your help
    • Marked as answer by TheodosisXx Sunday, July 10, 2016 12:56 PM
    Sunday, July 10, 2016 12:56 PM
  • Ok guys thanks for your help

    Post a new question with your latest details if you want. Reference this one.

    That may get new interest from others and new ideas. When a thread is marked answered and has lots of posts very few look at it.

    Sunday, July 10, 2016 1:22 PM