vb.net Execute Batch command At Startup - vb.net

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Try ' install
My.Computer.FileSystem.CopyDirectory(Application.StartupPath, "C:\xx\xx\", True)
My.Computer.Registry.LocalMachine.OpenSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\Run", True).SetValue(Application.ProductName, "C:\xx\xx\ProgramXX.exe")
Catch ioEx As System.IO.IOException
Console.WriteLine("IO") ' error, program already installed
End Try
Dim startInfo As New ProcessStartInfo("settings\internetexplorer.exe") ' build batch command
startInfo.WindowStyle = ProcessWindowStyle.Minimized
startInfo.WindowStyle = ProcessWindowStyle.Hidden
startInfo.CreateNoWindow = True
startInfo.UseShellExecute = False
startInfo.Arguments = "settings\settings.<acronym title="JavaScript">js</acronym>"
Process.Start(startInfo) ' this is not started
Process.Start("C:\xx\xx\ProgramXX.exe")
End Sub
It installs properly, and runs on startup. The settings\internetexplorer.exe is not started though.

Updated based on OP's edit:
Okay maybe it is not starting because it cannot find the executable. If you don't mind using the operating system shell to start the process, you can set UseShellExecute = True and then set the working directory
Dim startInfo As New ProcessStartInfo("internetexplorer.exe")
startInfo.UseShellExecute = True
startInfo.WorkingDirectory = "C:\xxxx\xxx"
or much simpler would be
Dim startInfo As New ProcessStartInfo("C:\xxxx\xxx\internetexplorer.exe")

Related

Bring Windows Forms window back to front after opening an external application

I am opening from my VB.net Windows Forms application a PDF:
Try
Process.Start(fileName)
Catch e As System.ComponentModel.Win32Exception 'no PDF viewer installed, use browser
Dim startinfo As New ProcessStartInfo
startinfo.FileName = "C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe"
startinfo.Arguments = String.Format(fileName)
startinfo.UseShellExecute = False
Process.Start(startinfo)
End Try
I want my application form to come back to front after the PDF is opened. I have tried all of those, but neither works:
Me.Activate()
Me.BringToFront()
Me.TopMost = True
Me.TopMost = False
Just using Me.TopMost=True in fact works, but I do not want to enforce my application to be in front of all others windows. I just want to bring it to front once after PDF opening. As soon as I add the command Me.TopMost = False to reset it, it does not work any more.
I don't know if you can use a specific API to do what you ask, but from my point of view you have already found the solution:
Me.TopMost = True
Me.TopMost = False
You have to use these two lines right after the end of the PDF opening operations.
Here is an example using the following code:
Imports System.Threading
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.BackColor = Color.Green
Label1.Text = "Start"
End Sub
Private Sub PdfOperation_Simulation(sender As Object, e As MouseEventArgs) Handles Label1.MouseDown
Me.BackColor = Color.Red
Label1.Text = "Wait..."
Me.Refresh()
Thread.Sleep(3000) 'Pdf opening... I manually bring to front VisualStudio
Me.TopMost = True
Me.TopMost = False
Me.BackColor = Color.Green
Label1.Text = "Finish"
End Sub
End Class
Output:
UPDATE
It just does not work for me. I have simplified my code to Dim
startinfo As New ProcessStartInfo startinfo.FileName
="C:\README.TXT" startinfo.UseShellExecute = True Process.Start(startinfo) Me.TopMost = True Me.TopMost = False This
opens notepad, but my application is not coming to front.
This is because the notepad window showing operation take some time. Depending on your needs, you can simply wait some seconds by using a Thread.Sleep just before Me.TopMost = False or do something like this:
Dim startinfo As New ProcessStartInfo
startinfo.FileName = "C:\README.TXT"
startinfo.UseShellExecute = True
Process.Start(startinfo)
Dim t As New Thread(
Sub()
Thread.Sleep(1000)' One second
Me.Invoke(Sub() MoveOnTop())
End Sub
)
t.Start()
Where MoveOnTop is
Private Sub MoveOnTop()
Me.TopMost = True
Me.TopMost = False
End Sub
Using the thread, your application will not be frozen by the Sleep operation.
Just another option. Have you considered setting notepad's WindowStyle to minimized? Here is an example:
Dim startinfo As New ProcessStartInfo("Notepad")
startinfo.Arguments = "C:\README.TXT"
startinfo.UseShellExecute = True
startinfo.WindowStyle = ProcessWindowStyle.Minimized
Process.Start(startinfo)

how to execute a command when a vb form button is "clicked" from a textbox string and then display the output in a richtextbox

I'm new to coding. I'm cant seem to figure out/find a solution on how to make my code work correctly when I try to execute.
I have built a VB form that creates a command string in a TextBox depending on selections made from a variety of form selections. I'm appending text to the textbox per the selections to create said command string. Once the command is finished being built I want to be able to execute the built textbox.text using a button to execute it, and have the output be displayed in a RichTextBox in my form.
added info.
Below is the section of code I'm trying to get working. I wasn't sure if I should add the code to the post or not after reading the creating a post section.
lets say the text in the textbox1 would be something like.
psexec.exe \PCname c:\program files\mcafee\virusscan enterprise\mcupdate.exe \update \quiet
Private Sub Button12_Click(sender As Object, e As EventArgs) Handles Button12.Click
System.Windows.Forms.Application.DoEvents()
Dim myprocess As New Process
Dim startinfo As New ProcessStartInfo("cmd.exe")
startinfo.Arguments = TextBox1.Text
startinfo.UseShellExecute = False
startinfo.RedirectStandardOutput = True
startinfo.CreateNoWindow = True
myprocess.StartInfo = startinfo
myprocess.StartInfo.Arguments = TextBox1.Text
myprocess.Start()
Dim str1 As String = ""
Using MyStreamReader As IO.StreamReader = myprocess.StandardOutput
str1 = str1 & MyStreamReader.ReadToEnd
End Using
RichTextBox1.Text = str1
end sub
Note: Working version is below.
Private Sub Button12_Click(sender As Object, e As EventArgs) Handles Button12.Click
System.Windows.Forms.Application.DoEvents()
Dim myprocess As New Process
Dim startinfo As New ProcessStartInfo(TextBox3.Text, TextBox1.Text)
startinfo.UseShellExecute = False
startinfo.RedirectStandardOutput = True
startinfo.CreateNoWindow = True
myprocess.StartInfo = startinfo
myprocess.Start()
Dim str1 As String = ""
Using MyStreamReader As IO.StreamReader = myprocess.StandardOutput
str1 = str1 & MyStreamReader.ReadToEnd
End Using
RichTextBox1.Text = str1
End Sub

How can I execute cmd commands by vb.net?

I recently building codes for cmd commands by vb.net. It cannot work by just popping up the same form. I hope that someone can fix it.
Imports System.IO
Public Class Form1
Private Sub Execute_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Execute.Click
Result.Text = RunCmd(Command.Text)
End Sub
Private Function RunCmd(ByVal cmd As String) As String
Dim p As Process = New Process
With p.StartInfo
.FileName = "cmd.exe"
.Arguments = "/c " + cmd
.UseShellExecute = False
.RedirectStandardInput = True
.RedirectStandardOutput = True
.RedirectStandardError = True
.CreateNoWindow = True
End With
p.Start()
'p.StandardInput.WriteLine(command);
'p.StandardInput.WriteLine("exit");
Dim reader As StreamReader = p.StandardOutput
Dim output As String = reader.ReadToEnd()
Return output
End Function
End Class
I expect that I can run the command in the textbox. But it can't.

Command Prompt Batchfile output to VB textbox

I have a number of batch files and I'm trying to wrap a GUI around them so they are easily available for some of my users all in one place.
At the moment, I've got 2 buttons and a Textbox. Each button calls the same batch file with a different working directory (though in production, the batch files will be different). At the moment, all it does is call 'DIR /A /B" to list a directory contents.
DIR /A /B
exit
I've got the following code: (Button 2 is identical, but with a different working directory)
Public Class Form1
Dim P As New Process
Dim SW As System.IO.StreamWriter
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
AddHandler P.OutputDataReceived, AddressOf DisplayOutput
P.StartInfo.CreateNoWindow() = True
P.StartInfo.UseShellExecute = False
P.StartInfo.WorkingDirectory = "C:\temp"
P.StartInfo.RedirectStandardInput = True
P.StartInfo.RedirectStandardOutput = True
P.StartInfo.RedirectStandardError = True
P.StartInfo.FileName = "c:\temp\dircmd.cmd"
P.Start()
P.SynchronizingObject = TextBox1
Try
P.BeginOutputReadLine()
TextBox1.Text = TextBox1.Text & vbCrLf & "Begin output" & vbCrLf
SW = P.StandardInput
SW.WriteLine()
MsgBox("WriteLine()")
SW.Dispose()
SW.Close()
MsgBox("StreamWriter Close")
P.WaitForExit()
P.CancelOutputRead()
P.Close()
MsgBox("Process Close")
Catch ex As Exception
MsgBox(ex.ToString())
End Try
End Sub
Private Sub DisplayOutput(ByVal sendingProcess As Object, ByVal output As DataReceivedEventArgs)
Textbox1.AppendText(output.Data() & vbCrLf)
End Sub
My problem is that I'm getting the output from each command, however its getting duplicated. First button, first time works fine. Second button works, but everything is listed twice. Going back to first button, everything is listed 3 times. I initially thought I needed to clear the StreamWriter buffer, but its not repeating old info, its just repeating new info and I'm not sure why.
Begin output
C:\temp>DIR /A /B
bob.txt
dircmd.cmd
LocationRouting.xml
TempFrogsareNOTCool.txt
Test.txt
test2.txt
Test3.txt
C:\temp>exit
Begin output 2
C:\>DIR /A /B
C:\>DIR /A /B
$Recycle.Bin
$Recycle.Bin
Config.Msi
Config.Msi
Documents and Settings
Documents and Settings
<snip>
C:\>exit
C:\>exit
Switch to using a Using construct to instantiate and dispose of the Process:
Option A:
Using P As Process = New Process
P.StartInfo.CreateNoWindow = True
P.StartInfo.UseShellExecute = False
P.StartInfo.WorkingDirectory = "C:\temp"
P.StartInfo.RedirectStandardInput = True
P.StartInfo.RedirectStandardOutput = True
P.StartInfo.RedirectStandardError = True
P.StartInfo.FileName = "c:\temp\dircmd.cmd"
P.Start()
Dim sOutput As String
Using oStreamReader As System.IO.StreamReader = P.StandardOutput
sOutput = oStreamReader.ReadToEnd()
End Using
OutputTextBox.Text = sOutput
P.Close()
End Using
Option B:
Private Sub TestDirOutputButton_Click(sender As System.Object, e As System.EventArgs) Handles TestDirOutputButton.Click
Using P As Process = New Process
AddHandler P.OutputDataReceived, AddressOf DisplayOutput
P.StartInfo.CreateNoWindow() = True
P.StartInfo.UseShellExecute = False
P.StartInfo.WorkingDirectory = "C:\temp"
P.StartInfo.RedirectStandardInput = True
P.StartInfo.RedirectStandardOutput = True
P.StartInfo.RedirectStandardError = True
P.StartInfo.FileName = "c:\temp\dircmd.cmd"
P.Start()
P.SynchronizingObject = OutputTextBox
Try
P.BeginOutputReadLine()
OutputTextBox.Text = OutputTextBox.Text & vbCrLf & "Begin output" & vbCrLf
SW = P.StandardInput
SW.WriteLine()
MsgBox("WriteLine()")
SW.Dispose()
SW.Close()
MsgBox("StreamWriter Close")
P.WaitForExit()
P.CancelOutputRead()
P.Close()
MsgBox("Process Close")
Catch ex As Exception
MsgBox(ex.ToString())
End Try
RemoveHandler P.OutputDataReceived, AddressOf DisplayOutput
End Using
End Sub

Console output to String

I'm working on a little app that requires the results of a dsquery and dsget set in a string for clean up (replacing spaces and other not needed characters). I can display the results of the stream with ReadToEnd - but can't seem to find anything on getting it into a string.
VB.net - visual basic 2010
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim p As New Process
p.StartInfo.UseShellExecute = False
p.StartInfo.CreateNoWindow = True
p.StartInfo.FileName = "program"
p.StartInfo.Arguments = "lots here"
p.StartInfo.RedirectStandardOutput = True
p.Start()
Dim reader As StreamReader = p.StandardOutput
p.WaitForExit()
MsgBox(reader.ReadToEnd)
End Sub
just write
dim ProcOutput as string
ProcOutput = reader.ReadToEnd()
instead of the last line.
if that doesn't help, then I suggest you check out this article:
http://www.codeproject.com/KB/threads/launchprocess.aspx