VB.Net Printing PDF Fails (But equivalent works from PowerShell) - vb.net

I'm trying to write a small desktop app that just sits around and prints files as they get downloaded.
Sending a PDF file to the printer with PowerShell works fine and it prints:
.\AcroRd32.exe /N /T C:\Path\to\201402124_label.pdf "Brother QL-700"
However, doing the same in Visual Studio 2012 does not work. The Adobe Reader window opens with the label, and closes, but the file never show up at the printer to be printed. This doesn't make sense because this same code is currently working to send larger PDFs to a duplex printer in the same manner (just using a different printer saved in My.Settings):
For Each file As IO.FileInfo In files
If file.CreationTime > My.Settings.LastRunDate Then
MsgBox(file.Name)
Dim startInfo As New ProcessStartInfo
Dim proc As Process = New Process
startInfo.WindowStyle = ProcessWindowStyle.Hidden
startInfo.Verb = "print"
startInfo.Arguments = My.Settings.LabelPrinterSettings.PrinterName.ToString
startInfo.UseShellExecute = True
startInfo.CreateNoWindow = True
startInfo.FileName = file.FullName
proc.StartInfo = startInfo
proc.Start()
proc.WaitForInputIdle()
proc.CloseMainWindow()
End If
Next
I can't figure out why doing this over the CLI/PowerShell works, but not inside VB.net

Why not simply use Process.Start(String, String)? Much more straight forward and clean. You can then use the returned Diagnostics.Process to run your other commands like WaitForInputIdle().
You would probably use something like this:
Dim proc As Process = Process.Start("AcroRd32.exe", _
String.Format("/N /T {0} ""{1}""", _
"C:\Path\to\201402124_label.pdf", "Brother QL-700")

Related

Printing a .ZPL file to a zebra printer in vb.net. Visual Studio 2015 version

I already have the raw ZPL file ready to go, I just don't know how to set the printer I want to send it to and then send it. How would I do this?
Note: I have a batch script on my computer that I default all ZPL files to, which is a shell script that sends the file to the thermal printer on my computer. I want to get away from that and have all the commands within my application so I don't have to use an external script like that.
This is the code I have now that when ran it auto opens with my batch script:
Sub SaveLabel(ByRef labelFileName As String, ByRef labelBuffer() As Byte)
' Save label buffer to file
Dim myPrinter As New PrinterSettings
Dim LabelFile As FileStream = New FileStream(labelFileName, FileMode.Create)
LabelFile.Write(labelBuffer, 0, labelBuffer.Length)
LabelFile.Close()
' Display label
DisplayLabel(labelFileName)
End Sub
Sub DisplayLabel(ByRef labelFileName As String)
Dim info As System.Diagnostics.ProcessStartInfo = New System.Diagnostics.ProcessStartInfo(labelFileName)
info.UseShellExecute = True
info.Verb = "open"
info.WindowStyle = ProcessWindowStyle.Hidden
info.CreateNoWindow = True
System.Diagnostics.Process.Start(info)
End Sub
And this is my batch script:
copy %1 \\%ComputerName%\Zebra
To replicate the exact functionality of the batch file in VB.net:
Dim filename As String = System.IO.Path.GetFileName(labelFileName)
System.IO.File.Copy(
labelFileName,
Environment.ExpandEnvironmentVariables("\\%ComputerName%\Zebra\" & filename))
This copies the file using the method provided by the System.IO namespace. It also expands the %COMPUTERNAME% environment variable. This replaces all the code in the DisplayFile subroutine.

VB.NET Process.Start Arguments not passing to CMD

This is my first post here, so please go easy, I also have a good knowledge of VB.
I am making an app that is to create a WiFi hotspot at a click of a button so that I can use my laptop as a WiFi extender for my devices like my phone, however, I am doing this with command prompt. This is my code so far:
Private Sub Form1_Paint(sender As Object, e As PaintEventArgs) Handles Me.Paint
Dim startInfo As New ProcessStartInfo("cmd")
startInfo.WindowStyle = ProcessWindowStyle.Minimized
startInfo.Arguments = "netsh show wlan drivers"
Process.Start(startInfo)
End Sub
The problem is, it's not passing the arguments. Cmd launches fine but receives nothing.
Things I have tried:
1. Using process.start and ProcessStartInfo
2. Change working directory
3. Send arguments after cmd has launched (after process.start)
4. Change target framework
5. Run in x86 and x64
6. Run as administrator
7. Trying other commands such as "color 2f". Failed.
Any help would be greatly appreciated!
Edit: Not even the WindowStyle argument was passed.
You need to add
startInfo.Arguments = "/C netsh wlan show drivers"
without that flag (/C) the CMD command exits immediately and nothing is executed
In any case your command is wrong. The correct syntax is
netsh wlan show drivers
You could change your code to capture the output of the command in this way
Dim startInfo As New ProcessStartInfo("cmd")
startInfo.WindowStyle = ProcessWindowStyle.Minimized
startInfo.Arguments = "/C netsh wlan show drivers"
startInfo.RedirectStandardOutput = true
startInfo.UseShellExecute = false
startInfo.CreateNoWindow = true
Dim p = Process.Start(startInfo)
Dim result = p.StandardOutput.ReadToEnd()
p.Close()

Execute DOS command within console application VB

I need to be able to execute a DOS command, such as 'ipconfig', using a command line application in Visual Basic. I can simply use start.process("CMD", "ipconfig"), but that opens a new instance of CMD. I want to be able to run a command like I would with CMD, using a console application, without opening another CMD window. Thanks!
You can use this to run the ipconfig command in hidden console window and redirect the output to local variable. From here you can manipulate it as needed:
Dim cmdProcess As New Process
With cmdProcess
.StartInfo = New ProcessStartInfo("cmd.exe", "/C ipconfig")
With .StartInfo
.CreateNoWindow = True
.UseShellExecute = False
.RedirectStandardOutput = True
End With
.Start()
.WaitForExit()
End With
' Read output to a string variable.
Dim ipconfigOutput As String = cmdProcess.StandardOutput.ReadToEnd

Run already opened process in vb.net

I have a windows form that, on the click of a button, runs a process (MATLAB) and executes a file.
Dim myProcesses() As Process
myProcesses = Process.GetProcessesByName("Matlab")
If myProcesses.Count > 0 Then
'~~~~ what goes here? ~~~~
Else
Dim startInfo As New ProcessStartInfo
startInfo.FileName = "C:\Program Files\MATLAB\R2011b\bin\matlab.exe"
startInfo.WorkingDirectory = MatlabDir 'MatlabDir is defined elsewhere
startInfo.Arguments = "matlab.exe -r test_plot2"
Process.Start(startInfo)
End If
The above code opens MATLAB and executes the script "test_plot2.m" if MATLAB isn't already open. But what do I write in the first IF statement, if MATLAB is already open, and all I want to do is run the file?
Thanks in advance.
Its supposed to be the same. I mean, it doesn't matter if its opened or not, unless the application (Matlab) manages something different, then you have to guess how. Have you tried just using the same code?
Example:
Dim startInfo As New ProcessStartInfo
startInfo.FileName = "notepad.exe"
startInfo.Arguments = "C:\temp\test.txt"
Process.Start(startInfo)
It doesn't matter if you have Notepad already opened or not.

Pick up strings from cmd command? Process.StartInfo

so I've tried Process and starting a cmd.exe and send commands directly to that window. And then picking up the values written to the cmd.exe window.
The code looks like this:
Dim arrServers As ArrayList
Dim s(ListBoxServers.Items.Count) As String
ListBoxServers.Items.CopyTo(s, 0)
arrServers = New ArrayList(s)
Using P As New Process
P.StartInfo.FileName = "cmd.exe"
P.StartInfo.UseShellExecute = False
P.StartInfo.RedirectStandardOutput = True
P.StartInfo.RedirectStandardInput = True
P.Start()
For Each i In arrServers
P.StandardInput.WriteLine("query user " & txtBoxUsername.Text & " /server:" & i)
Next
P.StandardInput.WriteLine("exit")
Output = P.StandardOutput.ReadToEnd()
Trace.WriteLine(Output)
MsgBox(Output)
P.WaitForExit()
End Using
But is looks like it doesn't "press enter" or something. Meaning, I don't get any results from the command. I don't even get a "'command' is not recognized as an internal or external command, operable program or batch file." like you normally get if it doesn't understand the syntax.
Look into the Process class in the System.Diagnostics namespace for running your batch file.
Imagine the following really simple batch file called "hello.bat"
#ECHO OFF
echo Hello
You can call it and see "Hello" by using:
'Will hold the results of the batch
Dim Output As String
'Create a new process object
Using P As New Process()
'Set the script to run
P.StartInfo.FileName = "c:\scripts\hello.bat"
'My script doesn't take argument but this is where you would pass them
P.StartInfo.Arguments = ""
'Required to redirect output, don't both worrying what it means
P.StartInfo.UseShellExecute = False
'Tell the system that you want to see the output
P.StartInfo.RedirectStandardOutput = True
'Start your batch
P.Start()
'Read the entire contents of the outout
Output = P.StandardOutput.ReadToEnd()
'Wait until the batch is done running
P.WaitForExit()
End Using
'Do something with the output
Trace.WriteLine("Batch produced : " & Output)
Edit
Here's a version that doesn't run a batch but instead runs a couple of standard commands. We start by firing up a command shell to pass things to. One thing that sucks is that its hard to run a command, read the output and then run another command. The code below runs two commands back-to-back and dumps the entire result into a string. If you have a need for running a command, processing, running another command, I think you'll have to wire up something to StandardError and look at return codes. Before you do that, make sure you read up on problem with blocking and how other places solve it by wiring threads up such as here. Probably the easier way is to wrap this into a sub and call the sub once for each command.
'Will hold all of the text
Dim Output As String
'Create a new process object
Using P As New Process()
'Set the script to run the standard command shell
P.StartInfo.FileName = "cmd.exe"
'Required to redirect output, don't both worrying what it means
P.StartInfo.UseShellExecute = False
'Tell the system that you want to read/write to it
P.StartInfo.RedirectStandardOutput = True
P.StartInfo.RedirectStandardInput = True
'Start your batch
P.Start()
'Send your various commands
P.StandardInput.WriteLine("dir c:\")
P.StandardInput.WriteLine("ipconfig /all")
'Very important, send the "exit" command otherwise STDOUT will never close the stream
P.StandardInput.WriteLine("exit")
'Read the entire stream
Output = P.StandardOutput.ReadToEnd()
'Wait until the batch is done running
P.WaitForExit()
End Using
'Do something with the output
Trace.WriteLine(Output)
Edit 2
I'm having problems with the "query user" command in general, I can't get it to return anything for usernames with spaces in them even if I enclose the name in quotes. But here's a version that uses "quser" instead which does the exact same thing as far as I know.
'Will hold all of the text
Dim Output As String
'Create a new process object
Using P As New Process()
'Set the script to run the standard command shell
P.StartInfo.FileName = "cmd.exe"
'Required to redirect output, don't both worrying what it means
P.StartInfo.UseShellExecute = False
'Tell the system that you want to read/write to it
P.StartInfo.RedirectStandardOutput = True
P.StartInfo.RedirectStandardInput = True
'Start your batch
P.Start()
'Send your various commands
'Array of servers
Dim arrServers() As String = New String() {"SERVER1", "SERVER2"}
'Loop through array, wrap names with quotes in case they have spaces
For Each S In arrServers
P.StandardInput.WriteLine(String.Format("quser ""{0}"" /SERVER:{1}", Me.txtBoxUsername.Text, S))
Next
'Very important, send the "exit" command otherwise STDOUT will never close the stream
P.StandardInput.WriteLine("exit")
'Read the entire stream
Output = P.StandardOutput.ReadToEnd()
'Wait until the batch is done running
P.WaitForExit()
End Using
'Do something with the output
Trace.WriteLine(Output)
Use a library/class like NDesk's Options for flexible argument handling. If you don't want to use a external component, you'll have to loop over the arguments and process them manually:
For Each arg As String In Environment.GetCommandLineArgs()
Select Case arg
Case "/blah"
' process /blah '
Case "/foo"
' process foo '
Case Else
MsgBox "Unknown argument " + arg " found, aborting.", vbCritical
Environment.Exit(1)
End Select
Next
[I normally don't do VB, so this is just an untested sketch]