Finally
enter code here
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim arg As String
arg = " -X POST -H ""Authorization: Bearer LINE TOKEN HERE"" -F ""message=TEST"" -F ""imageFile=#C:\charts\PIC.png"" https://notify-api.line.me/api/notify"
ShellandWait("curl.exe", arg)
End Sub
Public Sub ShellandWait(ByVal ProcessPath As String, ByVal Arguments As String)
Dim objProcess As System.Diagnostics.Process
Try
objProcess = New System.Diagnostics.Process()
objProcess.StartInfo.Arguments = Arguments
objProcess.StartInfo.FileName = ProcessPath
objProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
objProcess.Start()
Application.DoEvents()
objProcess.WaitForExit()
Application.DoEvents()
Console.WriteLine(objProcess.ExitCode.ToString())
objProcess.Close()
Catch ex As Exception
MsgBox("Could not start process " & ProcessPath & " " & ex.StackTrace.ToString)
End Try`
End Sub
This is not an answer, but, because of my current reputation, I cannot write comments. I feel the need to inform you that blocked out codes in the image you linked are not properly hidden. It is possible to read the top one. I suggest you always use a completely opaque brush to hide important information.
I know that this is not how info is usually sent on StackOverflow, but figured that this guy's privacy is more important than convention in this scenario.
Have you tried the following:
Dim prc as Process
prc = New Process
prc = Process.Start([YourBatchFileLocation])
prc = Nothing
Or, you could also try the following:
Shell([YourBatchFileLocation], AppWinStyle.NormalFocus, True)
Related
I'm in need of help with this program which I'm trying to create.
I'm pretty new to programming in general, so please bear with me.
So what I'm trying to create right now, is my own command prompt, and with that said, let me tell you what I want in the command prompt.
As we know from the normal CMD on windows OS systems, we have our input box(or whatever) which we can use to type commands, such as "start google.com", or "ipconfig" etc...
and we have our output, which tells us the results from the commands we typed.
And I wanna create the exact same thing, just with my own UI and some extras which I'm gonna add later.
Here is my issue tho, whenever I type the shell command in my textbox and execute it, it prints out the exception message, so basically it doesn't run the command.
Here is the code:
Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress
Dim tmp As System.Windows.Forms.KeyPressEventArgs = e
If tmp.KeyChar = ChrW(Keys.Enter) Then
Try
Shell(TextBox1.Text)
RichTextBox1.SelectionColor = Color.Green
RichTextBox1.SelectedText = TextBox1.Text
Catch ex As Exception
RichTextBox1.Clear()
RichTextBox1.SelectionColor = Color.Red
RichTextBox1.SelectedText = ex.Message
End Try
TextBox1.Text = ""
Else
End If
End Sub
I'd really like some examples if possible, since I'm new and I probably wouldn't understand much without examples.
Using a process object instead of a shell is a lot better of an option for having a conversation with cmd. Here's an example of a simple function that you can pass commands to that will return the command's response. This example just does one command/response, but you can use the same process shown below to enter into a dialog with cmd.exe:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
MsgBox(ExecuteCommand("ipconfig /all"))
End Sub
Private Function ExecuteCommand(ByVal command As String) As String
Dim response As String = Nothing
Dim p As New System.Diagnostics.Process
Dim psi As New System.Diagnostics.ProcessStartInfo("cmd.exe")
With psi
.UseShellExecute = False
.RedirectStandardInput = True
.RedirectStandardOutput = True
.RedirectStandardError = True
.CreateNoWindow = True
End With
p = Process.Start(psi)
With p
.StandardInput.WriteLine(command)
.StandardInput.Close()
If .StandardError.Peek > 0 Then
response = .StandardError.ReadToEnd
.StandardError.Close()
Else
response = .StandardOutput.ReadToEnd
.StandardOutput.Close()
End If
.Close()
End With
Return response
End Function
And as you'll see if you run the code above, you can certainly use commands like ipconfig
After a few days of googeling and trying i thought let met ask it my self.
I am trying to make this happen:
http://gyazo.com/5274568fcb55a0fe042936e375c0b424
The show current routes is working just fine, and displays the text i ask him to show.
But the route adding not so much let me show you the code :)
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim cmdThread As New Threading.Thread(AddressOf CmdAutomate2)
cmdThread.Start()
End Sub
Private Sub CmdAutomate2()
Dim myprocess As New Process
Dim startInfo As New System.Diagnostics.ProcessStartInfo
startInfo.FileName = "cmd"
startInfo.RedirectStandardInput = True
startInfo.RedirectStandardOutput = True
startInfo.UseShellExecute = False
startInfo.CreateNoWindow = True
myprocess.StartInfo = startInfo
myprocess.Start()
Dim sR As System.IO.StreamReader = myprocess.StandardOutput
Dim sW As System.IO.StreamWriter = myprocess.StandardInput
sW.WriteLine("route add" & textbox1.text & " " & textbox2.text)
sW.WriteLine("exit") 'exits command prompt window
results = sR.ReadToEnd 'returns results of the command window
sW.Close()
sR.Close()
Invoke(finished)
End Sub
Now i know you should use different pieces of code here mainly:
startInfo.UseShellExecute = True
instead of:
startInfo.UseShellExecute = False
But that gives me errors with the redirect (which i found to be confimed as not possible somewhere else in this forum)
Now i dont care for it to show the output i have the other button for it.
But i cannot seem to et this to work as i get different errors all the time like cannot reditect ot redirect not started with different combinations of code from all over the web,,
What am i missing here??
To be able to edit the route table for your PC, your app needs to run as administrator. you can add a manifest to your application which declares that you require administrator privileges, which should prompt as required.
This is my first question here because I ended up in dead end.
I'm using ZIP 2 Secure EXE (very good software from Chilkat) to create setup.exe for application. ZIP 2 Secure EXE can be run without GUI with one or more parameters.
The problem is that when I call ZIP 2 Secure EXE (ChilkatZipSE.exe) without using OpenFileDialog form to determine location of ChilkatZipSE.exe, it doesn't run process with System.Diagnostics.Process class. The way I call ChilkatZipSE.exe is "..\ChilkatZipSE.exe -cfg settings.xml". Everything is OK with settings.xml and there is UnlockCode node which is needed for creating setup.exe file. When I use OpenFileDialog ChilkatZipSE.exe creates desired setup.exe and it's working fine.
Bellow is my code that I use:
Private Sub btnStartApp_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStartApp.Click
If txtExtAppPath.Text.Length > 0 AndAlso System.IO.File.Exists(txtExtAppPath.Text) Then
Dim myFile As New FileInfo(txtExtAppPath.Text)
txtExtAppLog.Text = StartApplication(myFile.FullName, txtExtParams.Text, chkIsHidden.Checked)
'txtExtAppLog.Text = StartApplication(txtExtAppPath.Text, txtExtParams.Text, chkIsHidden.Checked)
End If
End Sub
Public Function StartApplication(ByVal fileFullPath_ As String, ByVal fileParameter_ As String, ByVal isHidden_ As Boolean) As String
Dim lassie As String = String.Empty
Try
Dim newProcess As New ProcessStartInfo()
newProcess.FileName = fileFullPath_
newProcess.Arguments = fileParameter_
If isHidden_ Then newProcess.WindowStyle = ProcessWindowStyle.Hidden
If System.IO.File.Exists(fileFullPath_) Then
Using startedNewProcess As Process = Process.Start(newProcess)
'startedNewProcess.EnableRaisingEvents = True
startedNewProcess.WaitForExit()
End Using
Else
lassie = "File " + fileFullPath_ + " doesn't exist."
End If
Catch ex As Exception
lassie = ex.Message
End Try
Return lassie
End Function
Thanks, magnumx.
the problem was the given parameter. When using OpenFileDialog it knows where settings.xml is. But when calling "..\ChilkatZipSE.exe -cfg settings.xml" without OpenFileDialog it must be used as "..\ChilkatZipSE.exe -cfg ..\settings.xml"
ok, please do no laugh at this :x
i'm trying to create a simple software testing tool in VB.NET
i created a simple C program PROG.EXE which scans a number and prints the OUTPUT, and started building my tester, it should execute PROG.EXE output.txt, so PROG.EXE takes input from input.txt and prints the output to output.txt
but i failed, at first i tried Process.start then shell but nothing worked !
so i did this trick, the VB.NET codes generate a batch file with this codes PROG.EXE output.txt, but again i failed, though the VB.NET created the batch file and executes too, but nothing happened ! but when i manually run the batch file i got success !
i tried executing the batchfile then sendkey the VBCR/LF/CRLF still nothing happens !
whats wrong ?
My VB.NET Code, i am using Visual Studio 2010 Professional
Option Explicit On
Option Strict On
Public Class Form1
Dim strFileName As String
Private Sub btnRun_Click() Handles btnRun.Click
Dim strOutput As String
Using P As New Process()
P.StartInfo.FileName = strFileName
P.StartInfo.Arguments = txtInput.Text
P.StartInfo.RedirectStandardOutput = True
P.StartInfo.UseShellExecute = False
P.StartInfo.WindowStyle = ProcessWindowStyle.Hidden ' will this hide the console ?
P.Start()
Using SR = P.StandardOutput
strOutput = SR.ReadToEnd()
End Using
End Using
txtOutput.Text = strOutput
End Sub
Private Sub btnTarget_Click() Handles btnTarget.Click
dlgFile.ShowDialog()
strFileName = dlgFile.FileName
lblFileName.Text = strFileName
End Sub
End Class
And this is my C code
#include<stdio.h>
#include<conio.h>
void main()
{
int x;
scanf("%d",&x);
printf("%d",(x*x));
}
my program runs perfectly when i run prog.exe <input.txt> output.txt in console
Below is a fully working example. You want to use the Process class as you tried but you need to RedirectStandardOutput on the process's StartInfo. Then you can just read the process's StandardOutput. The sample below is written using VB 2010 but works pretty much the same for older versions.
Option Explicit On
Option Strict On
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
''//This will hold the entire output of the command that we are running
Dim T As String
''//Create our process object
Using P As New Process()
''//Pass it the EXE that we want to execute
''//NOTE: you might have to use an absolute path here
P.StartInfo.FileName = "ping.exe"
''//Pass it any arguments needed
''//NOTE: if you pass a file name as an argument you might have to use an absolute path
P.StartInfo.Arguments = "127.0.0.1"
''//Tell the process that we want to handle the commands output stream
''//NOTE: Some programs also write to StandardError so you might want to watch that, too
P.StartInfo.RedirectStandardOutput = True
''//This is needed for the previous line to work
P.StartInfo.UseShellExecute = False
''//Start the process
P.Start()
''//Wrap a StreamReader around the standard output
Using SR = P.StandardOutput
''//Read everything from the stream
T = SR.ReadToEnd()
End Using
End Using
''//At this point T will hold whatever the process with the given arguments kicked out
''//Here we are just dumping it to the screen
MessageBox.Show(T)
End Sub
End Class
EDIT
Here is an updated version that reads from both StandardOutput and StandardError. This time it reads asynchronously. The code calls the CHOICE exe and passes an invalid command line switch which will trigger writing to StandardError instead of StandardOutput. For your program you should probably monitor both. Also, if you're passing a file into the program make sure that you are specifying the absolute path to the file and make sure that if you have spaces in the file path that you are wrapping the path in quotes.
Option Explicit On
Option Strict On
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
''//This will hold the entire output of the command that we are running
Dim T As String
''//Create our process object
Using P As New Process()
''//Pass it the EXE that we want to execute
''//NOTE: you might have to use an absolute path here
P.StartInfo.FileName = "choice"
''//Pass it any arguments needed
''//NOTE: if you pass a file name as an argument you might have to use an absolute path
''//NOTE: I am passing an invalid parameter to show off standard error
P.StartInfo.Arguments = "/G"
''//Tell the process that we want to handle the command output AND error streams
P.StartInfo.RedirectStandardOutput = True
P.StartInfo.RedirectStandardError = True
''//This is needed for the previous line to work
P.StartInfo.UseShellExecute = False
''//Add handlers for both of the data received events
AddHandler P.ErrorDataReceived, AddressOf ErrorDataReceived
AddHandler P.OutputDataReceived, AddressOf OutputDataReceived
''//Start the process
P.Start()
''//Start reading from both error and output
P.BeginErrorReadLine()
P.BeginOutputReadLine()
''//Signal that we want to pause until the program is done running
P.WaitForExit()
Me.Close()
End Using
End Sub
Private Sub ErrorDataReceived(ByVal sender As Object, ByVal e As DataReceivedEventArgs)
Trace.WriteLine(String.Format("From Error : {0}", e.Data))
End Sub
Private Sub OutputDataReceived(ByVal sender As Object, ByVal e As DataReceivedEventArgs)
Trace.WriteLine(String.Format("From Output : {0}", e.Data))
End Sub
End Class
Its important that you put your entire file path in quotes if it has spaces in it (in fact, you should always enclose it in quotes just in case.) For instance, this won't work:
P.StartInfo.FileName = "attrib"
P.StartInfo.Arguments = "C:\Program Files\Windows NT\Accessories\wordpad.exe"
But this will:
P.StartInfo.FileName = "attrib"
P.StartInfo.Arguments = """C:\Program Files\Windows NT\Accessories\wordpad.exe"""
EDIT 2
Okay, I'm an idiot. I thought you were just wrapping a filename in angled brackets like <input.txt> or [input.txt], I didn't realize that you were using actual stream redirectors! (A space before and after input.txt would have helped.) Sorry for the confusion.
There are two ways to handle stream redirection with the Process object. The first is to manually read input.txt and write it to StandardInput and then read StandardOutput and write that to output.txt but you don't want to do that. The second way is to use the Windows command interpreter, cmd.exe which has a special argument /C. When passed it executes any string after it for you. All stream redirections work as if you typed them at the command line. Its important that whatever command you pass gets wrapped in quotes so along with the file paths you'll see some double-quoting. So here's a version that does all that:
Option Explicit On
Option Strict On
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
''//Full path to our various files
Dim FullExePath As String = "C:\PROG.exe"
Dim FullInputPath As String = "C:\input.txt"
Dim FullOutputPath As String = "C:\output.txt"
''//This creates our command using quote-escaped paths, all completely wrapped in an extra set of quotes
''//""C:\PROG.exe" < "C:\input.txt" > "C:\output.txt""
Dim FullCommand = String.Format("""""{0}"" < ""{1}"" > ""{2}""""", FullExePath, FullInputPath, FullOutputPath)
''//Create our process object
Using P As New Process()
''//We are going to use the command shell and tell it to process our command for us
P.StartInfo.FileName = "cmd"
''//The /C (capitalized) means "execute whatever else is passed"
P.StartInfo.Arguments = "/C " & FullCommand
''//Start the process
P.Start()
''//Signal to wait until the process is done running
P.WaitForExit()
End Using
Me.Close()
End Sub
End Class
EDIT 3
The entire command argument that you pass to cmd /C needs to be wrapped in a set of quotes. So if you concat it it would be:
Dim FullCommand as String = """""" & FullExePath & """" & " <""" & FullInputPath & """> " & """" & FullOutputPath & """"""
Here's what the actual command that you pass should look like:
cmd /C ""C:\PROG.exe" < "C:\INPUT.txt" > "C:\output.txt""
Here's a full code block. I've added back the error and output readers just in case you're getting a permission error or something. So look at the Immediate Window to see if any errors are kicked out. If this doesn't work I don't know what to tell you.
Option Explicit On
Option Strict On
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
''//Full path to our various files
Dim FullExePath As String = "C:\PROG.exe"
Dim FullInputPath As String = "C:\INPUT.txt"
Dim FullOutputPath As String = "C:\output.txt"
''//This creates our command using quote-escaped paths, all completely wrapped in an extra set of quotes
Dim FullCommand As String = """""" & FullExePath & """" & " <""" & FullInputPath & """> " & """" & FullOutputPath & """"""
Trace.WriteLine("cmd /C " & FullCommand)
''//Create our process object
Using P As New Process()
''//We are going to use the command shell and tell it to process our command for us
P.StartInfo.FileName = "cmd"
''//Tell the process that we want to handle the command output AND error streams
P.StartInfo.RedirectStandardError = True
P.StartInfo.RedirectStandardOutput = True
''//This is needed for the previous line to work
P.StartInfo.UseShellExecute = False
''//Add handlers for both of the data received events
AddHandler P.ErrorDataReceived, AddressOf ErrorDataReceived
AddHandler P.OutputDataReceived, AddressOf OutputDataReceived
''//The /C (capitalized) means "execute whatever else is passed"
P.StartInfo.Arguments = "/C " & FullCommand
''//Start the process
P.Start()
''//Start reading from both error and output
P.BeginErrorReadLine()
P.BeginOutputReadLine()
''//Signal to wait until the process is done running
P.WaitForExit()
End Using
Me.Close()
End Sub
Private Sub ErrorDataReceived(ByVal sender As Object, ByVal e As DataReceivedEventArgs)
Trace.WriteLine(String.Format("From Error : {0}", e.Data))
End Sub
Private Sub OutputDataReceived(ByVal sender As Object, ByVal e As DataReceivedEventArgs)
Trace.WriteLine(String.Format("From Output : {0}", e.Data))
End Sub
End Class
Public Class attributeclass
Public index(7) As ctrarray
End Class
Public Class ctrarray
Public nameclass As String
Public ctrlindex(10) As ctrlindexclass
End Class
Public Class ctrlindexclass
Public number As Integer
Public names(10) As String
Public status(10) As Boolean
Sub New()
number = 0
For i As Integer = 0 To 10
names(i) = "N/A"
status(i) = False
Next
End Sub
End Class
Public attr As New attributeclass
Sub Main()
attr.index(1).nameclass = "adfdsfds"
System.Console.Write(attr.index(1).nameclass)
System.Console.Read()
End Sub
I neet to get UNC path from mapped drive.
I tried to use WNetGetConnection, but it doesn't work for me. It returns error 487.
Does anybody know how to deal with this error or any other way to get the UNC path?
Totally go with #Alex K's P/Invoke suggestion, I just wanted to post a hack method of piping through the net use command:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim RemotePath = GetUncSourcePath("v"c)
If String.IsNullOrEmpty(RemotePath) Then
Trace.WriteLine("there was an error")
Else
Trace.WriteLine(RemotePath)
End If
Me.Close()
End Sub
Private Shared Function GetUncSourcePath(ByVal driveLetter As Char) As String
If String.IsNullOrEmpty(driveLetter) Then Throw New ArgumentNullException("driveLetter")
If (driveLetter < "a"c OrElse driveLetter > "z") AndAlso (driveLetter < "A"c OrElse driveLetter > "Z") Then Throw New ArgumentOutOfRangeException("driveLetter", "driveLetter must be a letter from A to Z")
Dim P As New Process()
With P.StartInfo
.FileName = "net"
.Arguments = String.Format("use {0}:", driveLetter)
.UseShellExecute = False
.RedirectStandardOutput = True
.CreateNoWindow = True
End With
P.Start()
Dim T = P.StandardOutput.ReadToEnd()
P.WaitForExit()
For Each Line In Split(T, vbNewLine)
If Line.StartsWith("Remote name") Then Return Line.Replace("Remote name", "").Trim()
Next
Return Nothing
End Function
You can use the WNetGetUniversalName API.
Works good for me and simpler than an api call like on http://vbnet.mvps.org/index.html?code/network/uncfrommappeddrive.htm
The only thing is I had to add a line of code to Dim the variable Line.
Thanks for the help