?
Solved

How to run a DOS command in VB application without displaying the Window's DOS shell window?

Posted on 2005-03-06
7
Medium Priority
?
170 Views
Last Modified: 2008-01-09
I am using the code below and it's working fine.But when it executes it brings up the Window's DOS shell also loses the focus I just want to get rid of that Window's DOS shell window!

Private Sub Command1_Click()
Dim oShell As Object
Dim oExec As Object
Dim sCmd As String
Dim sRetVal As String

'Command to execute, change to suit
sCmd = "%comspec% /c dir c:\"

Set oShell = CreateObject("WScript.Shell")
Set oExec = oShell.Exec(sCmd)

'Read everything at once
sRetVal = oExec.StdOut.ReadAll()

'The return value from the shelled process
Text2.Text = sRetVal

'Clean up
Set oExec = Nothing
Set oShell = Nothing
End Sub


Thanks in advance
0
Comment
Question by:imnajam
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
7 Comments
 
LVL 22

Expert Comment

by:DarkoLord
ID: 13469826
Hi, you could try that (credits go to "BuggyProgrammer"):

'Redirects output from console program to textbox.
'Requires two textboxes and one command button.
'Set MultiLine property of Text2 to true.
'
'Original bcx version of this program was made by
' dl <dl@tks.cjb.net>
'VB port was made by Jernej Simoncic <jernej@isg.si>
'Visit Jernejs site at http://www2.arnes.si/~sopjsimo/
'
'Note: don't run plain DOS programs with this example
'under Windows 95,98 and ME, as the program freezes when
'execution of program is finnished.

Option Explicit
Private Declare Function CreatePipe Lib "kernel32" (phReadPipe As Long, phWritePipe As Long, lpPipeAttributes As SECURITY_ATTRIBUTES, ByVal nSize As Long) As Long
Private Declare Sub GetStartupInfo Lib "kernel32" Alias "GetStartupInfoA" (lpStartupInfo As STARTUPINFO)
Private Declare Function CreateProcess Lib "kernel32" Alias "CreateProcessA" (ByVal lpApplicationName As String, ByVal lpCommandLine As String, lpProcessAttributes As Any, lpThreadAttributes As Any, ByVal bInheritHandles As Long, ByVal dwCreationFlags As Long, lpEnvironment As Any, ByVal lpCurrentDriectory As String, lpStartupInfo As STARTUPINFO, lpProcessInformation As PROCESS_INFORMATION) As Long
Private Declare Function SetWindowText Lib "user32" Alias "SetWindowTextA" (ByVal hwnd As Long, ByVal lpString As String) As Long
Private Declare Function ReadFile Lib "kernel32" (ByVal hFile As Long, lpBuffer As Any, ByVal nNumberOfBytesToRead As Long, lpNumberOfBytesRead As Long, lpOverlapped As Any) As Long
Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long

Private Type SECURITY_ATTRIBUTES
  nLength As Long
  lpSecurityDescriptor As Long
  bInheritHandle As Long
End Type

Private Type PROCESS_INFORMATION
  hProcess As Long
  hThread As Long
  dwProcessId As Long
  dwThreadId As Long
End Type

Private Type STARTUPINFO
  cb As Long
  lpReserved As Long
  lpDesktop As Long
  lpTitle As Long
  dwX As Long
  dwY As Long
  dwXSize As Long
  dwYSize As Long
  dwXCountChars As Long
  dwYCountChars As Long
  dwFillAttribute As Long
  dwFlags As Long
  wShowWindow As Integer
  cbReserved2 As Integer
  lpReserved2 As Byte
  hStdInput As Long
  hStdOutput As Long
  hStdError As Long
End Type

Private Type OVERLAPPED
    ternal As Long
    ternalHigh As Long
    offset As Long
    OffsetHigh As Long
    hEvent As Long
End Type

Private Const STARTF_USESHOWWINDOW = &H1
Private Const STARTF_USESTDHANDLES = &H100
Private Const SW_HIDE = 0
Private Const EM_SETSEL = &HB1
Private Const EM_REPLACESEL = &HC2

Private Sub Command1_Click()
  Command1.Enabled = False
  Redirect Text1.Text, Text2
  Command1.Enabled = True
End Sub
Private Sub Form_Load()
    Text1.Text = "ping"
End Sub
Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)
  If Command1.Enabled = False Then Cancel = True
End Sub

Sub Redirect(cmdLine As String, objTarget As Object)
  Dim i%, t$
  Dim pa As SECURITY_ATTRIBUTES
  Dim pra As SECURITY_ATTRIBUTES
  Dim tra As SECURITY_ATTRIBUTES
  Dim pi As PROCESS_INFORMATION
  Dim sui As STARTUPINFO
  Dim hRead As Long
  Dim hWrite As Long
  Dim bRead As Long
  Dim lpBuffer(1024) As Byte
  pa.nLength = Len(pa)
  pa.lpSecurityDescriptor = 0
  pa.bInheritHandle = True
 
  pra.nLength = Len(pra)
  tra.nLength = Len(tra)

  If CreatePipe(hRead, hWrite, pa, 0) <> 0 Then
    sui.cb = Len(sui)
    GetStartupInfo sui
    sui.hStdOutput = hWrite
    sui.hStdError = hWrite
    sui.dwFlags = STARTF_USESHOWWINDOW Or STARTF_USESTDHANDLES
    sui.wShowWindow = SW_HIDE
    If CreateProcess(vbNullString, cmdLine, pra, tra, True, 0, Null, vbNullString, sui, pi) <> 0 Then
      SetWindowText objTarget.hwnd, ""
      Do
        Erase lpBuffer()
        If ReadFile(hRead, lpBuffer(0), 1023, bRead, ByVal 0&) Then
          SendMessage objTarget.hwnd, EM_SETSEL, -1, 0
          SendMessage objTarget.hwnd, EM_REPLACESEL, False, lpBuffer(0)
          DoEvents
        Else
          CloseHandle pi.hThread
          CloseHandle pi.hProcess
          Exit Do
        End If
        CloseHandle hWrite
      Loop
      CloseHandle hRead
    End If
  End If
End Sub

change "ping" to command you wish to execute
0
 
LVL 15

Expert Comment

by:babuno5
ID: 13469870
try out this

Private Sub Command1_Click()

Dim oShell As Object
Dim oExec As Object
Dim sCmd As String
Dim sRetVal As String

'Command to execute, change to suit
sCmd = "cmd /c dir c:\"

Set oShell = CreateObject("WScript.Shell")
Set oExec = oShell.Exec(sCmd)

'Read everything at once
sRetVal = oExec.StdOut.ReadAll()

'The return value from the shelled process
Text2.Text = sRetVal
Text2.SetFocus
'Clean up
Set oExec = Nothing
Set oShell = Nothing

End Sub
0
 
LVL 7

Expert Comment

by:Smallint
ID: 13469971
If you don't need to get console respose, execute a dos command in a hidden window can be as simple as:

Call Shell(Environ("COMSPEC") & " /c copy YourDosCommand", vbHide)


Cheers
0
 
LVL 9

Author Comment

by:imnajam
ID: 13470010
thanks for the suggestion but I had found the solution before reading the comments here what I have done is

Set fso = CreateObject("Scripting.FileSystemObject")
outfile = App.Path & "\" & fso.GetTempName
errfile = App.Path & "\" & fso.GetTempName
ssCmd = "%comspec% /c" & txtcmd.Text & " 2>" & errfile & " 1>" & outfile
Set oShell = CreateObject("WScript.Shell")
oShell.run ssCmd, 0, True

   iFileNum = FreeFile
    Debug.Print outfile
    Open outfile For Input As iFileNum
    lFileLength = LOF(iFileNum)
    text2.Text = Input(lFileLength, #iFileNum)
    Close iFileNum
    fso.DeleteFile (errfile)
    fso.DeleteFile (outfile)
Set oExec = Nothing
Set oShell = Nothing

so this question should be "I've answered my question myself, delete/refund"
0
 

Accepted Solution

by:
modulo earned 0 total points
ID: 13793201
PAQed with points refunded (250)

modulo
Community Support Moderator
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction While answering a recent question (http://www.experts-exchange.com/Q_27402310.html) in the VB classic zone, I wrote some VB code in the (Office) VBA environment, rather than fire up my older PC.  I didn't post completely correct code o…
This article describes some techniques which will make your VBA or Visual Basic Classic code easier to understand and maintain, whether by you, your replacement, or another Experts-Exchange expert.
Get people started with the utilization of class modules. Class modules can be a powerful tool in Microsoft Access. They allow you to create self-contained objects that encapsulate functionality. They can easily hide the complexity of a process from…
Show developers how to use a criteria form to limit the data that appears on an Access report. It is a common requirement that users can specify the criteria for a report at runtime. The easiest way to accomplish this is using a criteria form that a…
Suggested Courses
Course of the Month8 days, 13 hours left to enroll

764 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question