I am making a C# Windows application for printing a PDF.
When I open the application, it only opens the Acrobat Reader window and no more printing. Is there anything I have missed in the function of Print()?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using Microsoft.Win32;
namespace PrintDocumentsApplication
{
public partial class PrintForm : Form
{
public PrintForm()
{
InitializeComponent();
}
private void printPdfButton_Click(object sender, EventArgs e)
{
String File = #"C:\Documents and Settings\larasasasrylo\Desktop\QRCODE_DEMO\test.pdf";
String Printer = "\\vhssadasdasoftaweafs\\HP Color LaserJet 5550 PCL 6";
Print(File, Printer);
}
public static bool Print(string file, string printer)
{
try
{
Process.Start(
Registry.LocalMachine.OpenSubKey(
#"SOFTWARE\Microsoft\Windows\CurrentVersion" +
#"\App Paths\AcroRd32.exe").GetValue("").ToString(),
string.Format("/h /t \"{0}\" \"{1}\"", file, printer));
return true;
}
catch { }
return false;
}
}
}
you try this
Process process = new Process();
process.StartInfo.FileName = pathToPdfOrDocFile;
process.UseShellExecute = true;
process.StartInfo.Verb = "printto";
process.StartInfo.Arguments = "\"" + printerName + "\"";
process.Start();
process.WaitForInputIdle();
process.Kill();
Related
I created this form :
I want to use the variable ffmpegArguments to pass the arguments from the textBox to the ffmpeg class arguments. the problem is that in the ffmpeg class i'm using the variables :
FileName and Framerate so how can i format the input from the textBox to the ffmpeg arguments with the FileName and Framerate variables ?
In the ffmpeg class :
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Capture_Screen
{
internal class FFmpeg_Capture
{
public string workingDirectory;
public string outputDirectory;
public string ffmpegArguments;
private Process process;
public FFmpeg_Capture()
{
}
public void Start(string FileName, int Framerate)
{
process = new Process();
process.StartInfo.FileName = outputDirectory; // Change the directory where ffmpeg.exe is.
process.EnableRaisingEvents = false;
process.StartInfo.WorkingDirectory = workingDirectory; // The output directory
process.StartInfo.Arguments = #"-y -f gdigrab -framerate " + Framerate +
" -i desktop -preset ultrafast -pix_fmt yuv420p " + FileName;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardInput = true; //Redirect stdin
process.StartInfo.CreateNoWindow = true;
process.Start();
}
public void Stop()
{
byte[] qKey = Encoding.GetEncoding("gbk").GetBytes("q"); //Get encoding of 'q' key
process.StandardInput.BaseStream.Write(qKey, 0, 1); //Write 'q' key to stdin of FFmpeg sub-processs
process.StandardInput.BaseStream.Flush(); //Flush stdin (just in case).
process.Close();
process.Dispose();
}
}
}
When i run this application i get an message that DeviceApplication.CAB installation was unsuccessfull .
I checked inside the windows directory and i found that wceload.exe is available.
I have placed the cab inside the directory where the present exe is running .
Any idea how to do this ??
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
namespace DeviceApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void displayMesage() {
LaunchInstaller("DeviceApplication.cab");
}
private static bool LaunchInstaller(string cabFile)
{
// Info on WceLoad.exe
//http://msdn.microsoft.com/en-us/library/bb158700.aspx
const string installerExe = "\\windows\\wceload.exe";
const string processOptions = "";
try
{
ProcessStartInfo processInfo = new ProcessStartInfo();
processInfo.FileName = installerExe;
processInfo.Arguments = processOptions + " \"" + cabFile + "\"";
Process process = Process.Start(processInfo);
if (process != null)
{
process.WaitForExit();
}
return InstallationSuccessCheck(cabFile);
}
catch (Exception e)
{
MessageBox.Show("Sorry, for some reason this installation failed.\n" + e.Message);
Console.WriteLine(e);
throw;
}
}
private static bool InstallationSuccessCheck(string cabFile)
{
if (File.Exists(cabFile))
{
MessageBox.Show("Something in the install went wrong. Please contact support.");
return false;
}
return true;
}
}
}
Answering my own question ,
Its because of the path i gave in the process ,
ProcessStartInfo psi = new ProcessStartInfo(#"Windows\wceload.exe", "/nodelete \"Program Files\\DeviceApplication3\\DeviceApplication.CAB\"");
Process proc = Process.Start(psi);
Tl:dr - How can I reference CasperJS and PhantomJS from the C# project folder?
I've got working code that runs a CasperJS script from a C# project when I manually unzip the binaries for CasperJS and PhantomJS to the C: drive. (See here for a simple guide and working code below labelled WORKING Code:)
As there is no installation needed I thought it would be easy enough to move these to the C# project folder instead \tools\casperjs and \tools\phantomjs. Also, I need to update the PATH variable in code using p.StartInfo.EnvironmentVariables["PATH"] = EnvPath;
All of the combination of paths I attempt I keep getting the following error "Fatal: [Errno 2] No such file or directory; did you install phantomjs?"
All of the files have definitely been included in the file path. Am I missing something obvious?
NON WORKING Code: [filepaths \tools\casperjs, \tools\phantomjs & C:\Python34]
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Casper
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string Cpath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
//;C:\phantomjs;C:\casperjs\batchbin
FileInfo csp1 = new FileInfo(Cpath + #"\tools\casperjs\n1k0-casperjs-4f105a9\bin\casperjs");
FileInfo csp2 = new FileInfo(Cpath + #"\tools\casperjs\batchbin");
FileInfo pht = new FileInfo(Cpath + #"\tools\phantomjs");
string EnvPath = string.Format(";{0};{1}", pht, csp2);
DirectoryInfo dir = csp1.Directory;
FileInfo path = new FileInfo(#"C:\Python34\python.exe");
string arg = String.Format("casperjs TESTcasper.js");
ExecutePythonScript(dir, path, arg, EnvPath);
}
private static void ExecutePythonScript(DirectoryInfo workingDir, FileInfo pythonPath, string casperArguments, string EnvPath)
{
var p = new Process();
p.StartInfo.EnvironmentVariables["PATH"] = EnvPath;
p.StartInfo.WorkingDirectory = workingDir.FullName;
p.StartInfo.FileName = pythonPath.FullName;
p.StartInfo.Arguments = casperArguments;
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.ErrorDataReceived += (s, e) =>
{
if (!string.IsNullOrEmpty(e.Data))
MessageBox.Show("e> " + e.Data);
};
p.OutputDataReceived += (s, e) =>
{
if (!string.IsNullOrEmpty(e.Data))
MessageBox.Show("->" + e.Data);
};
p.Start();
p.BeginOutputReadLine();
p.BeginErrorReadLine();
p.WaitForExit();
p.Close();
}
}
}
WORKING Code: [filepaths C:\casperjs, C:\phantomjs & C:\Python34]
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Casper
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//
FileInfo info = new FileInfo(#"C:\casperjs\n1k0-casperjs-4f105a9\bin\casperjs");
DirectoryInfo dir = info.Directory;
FileInfo path = new FileInfo(#"C:\Python34\python.exe");
string arg = #"casperjs TESTcasper.js";
ExecutePythonScript(dir, path, arg);
}
private static void ExecutePythonScript(DirectoryInfo workingDir, FileInfo pythonPath, string casperArguments)
{
var p = new Process();
p.StartInfo.WorkingDirectory = workingDir.FullName;
p.StartInfo.FileName = pythonPath.FullName;
p.StartInfo.Arguments = casperArguments;
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.ErrorDataReceived += (s, e) =>
{
if (!string.IsNullOrEmpty(e.Data))
MessageBox.Show("e> " + e.Data);
};
p.OutputDataReceived += (s, e) =>
{
if (!string.IsNullOrEmpty(e.Data))
MessageBox.Show("->" + e.Data);
};
p.Start();
p.BeginOutputReadLine();
p.BeginErrorReadLine();
p.WaitForExit();
p.Close();
}
}
}
TESTcasper.js
var casper = require('casper').create();
casper.start('http://casperjs.org/', function() {
this.echo(this.getTitle());
});
casper.thenOpen('http://phantomjs.org', function() {
this.echo(this.getTitle());
});
casper.run();
Got it working. Just make sure ALL required assets are properly copied over. I missed the file package.json in the filepath C:\casperjs\n1k0-casperjs-4f105a9
This now works for me
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Casper
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string Cpath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
//;C:\phantomjs;C:\casperjs\batchbin
FileInfo csp1 = new FileInfo(Cpath + #"\tools\casperjs\n1k0-casperjs-4f105a9\bin\casperjs");
FileInfo csp2 = new FileInfo(Cpath + #"\tools\casperjs\n1k0-casperjs-4f105a9\batchbin");
FileInfo pht = new FileInfo(Cpath + #"\tools\phantomjs\phantomjs-1.9.7-windows\");
string EnvPath = string.Format(";{0};{1}", pht, csp2);
DirectoryInfo dir = csp1.Directory;
FileInfo path = new FileInfo(#"C:\Python34\python.exe");
string arg = String.Format("casperjs OSTESTcasper.js");
ExecutePythonScript(dir, path, arg, EnvPath);
}
private static void ExecutePythonScript(DirectoryInfo workingDir, FileInfo pythonPath, string casperArguments, string EnvPath)
{
var p = new Process();
p.StartInfo.EnvironmentVariables["PATH"] = EnvPath;
p.StartInfo.WorkingDirectory = workingDir.FullName;
p.StartInfo.FileName = pythonPath.FullName;
p.StartInfo.Arguments = casperArguments;
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.ErrorDataReceived += (s, e) =>
{
if (!string.IsNullOrEmpty(e.Data))
MessageBox.Show("e> " + e.Data);
};
p.OutputDataReceived += (s, e) =>
{
if (!string.IsNullOrEmpty(e.Data))
MessageBox.Show("->" + e.Data);
};
p.Start();
p.BeginOutputReadLine();
p.BeginErrorReadLine();
p.WaitForExit();
p.Close();
}
}
}
I have tried to run the batch file from c# using the following code and i want to display the result in WPF textbox. Could you please guide me how to do this?
using System;
namespace Learn
{
class cmdShell
{
[STAThread] // Lets main know that multiple threads are involved.
static void Main(string[] args)
{
System.Diagnostics.Process proc; // Declare New Process
proc = System.Diagnostics.Process.Start("C:\\listfiles.bat"); // run test.bat from command line.
proc.WaitForExit(); // Waits for the process to end.
}
}
}
This batch file is to list the files from the folder. Once the batch is executed result should be displayed in the textbox. If the batch file having more than one commands, then result of each commands should be displayed in textbox.
You need to redirect the standard output stream:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace Test
{
class Program
{
static void Main(string[] args)
{
Process proc = new Process();
proc.StartInfo.FileName = "test.bat";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.Start();
string output = proc.StandardOutput.ReadToEnd();
Console.WriteLine(output); // or do something else with the output
proc.WaitForExit();
Console.ReadKey();
}
}
}
I have resolved the issues with process hanging and getting output instantly as below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace Test
{
class Program
{
static void Main(string[] args)
{
Process proc = new Process();
proc.StartInfo.FileName = "test.bat";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.OutputDataReceived += proc_OutputDataReceived;
proc.Start();
proc.BeginOutputReadLine();
}
}
void proc_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
this.Dispatcher.Invoke((Action)(() =>
{
txtprogress.Text = txtprogress.Text + "\n" + e.Data;
txtprogress.ScrollToEnd();
}));
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Security;
namespace SampleProject
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
String input = textBox1.Text;
try
{
Process ps = new Process();
ps.StartInfo.FileName = #"\\199.63.55.163\d$\hello.bat";
ps.StartInfo.Arguments = input;
ps.StartInfo.CreateNoWindow = false;
String domain = ps.StartInfo.Domain;
ps.StartInfo.RedirectStandardOutput = true;
ps.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
ps.StartInfo.WorkingDirectory = #"d:\praveen";
ps.StartInfo.UserName = "Raj";
ps.StartInfo.Domain = "domain";
ps.StartInfo.Password = Encrypt("Hello123");
ps.StartInfo.UseShellExecute = false;
ps.Start();
ps.WaitForExit();
MessageBox.Show(ps.StandardOutput.ReadToEnd());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void label1_Click(object sender, EventArgs e)
{
}
public static SecureString Encrypt(String pwd)
{
SecureString ss = new SecureString();
for (int i = 0; i < pwd.Length; i++)
{
ss.AppendChar(pwd[i]);
}
return ss;
}
}
}
It's a shot in the dark, but I think that you can't read the processes standard output once it has exited.
Also you have to redirect it - take a look at this documentation: http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardoutput.aspx
Duplicate of .NET Process Start Process Error using credentials (The handle is invalid) ? You need to assign RedirectStandardInput, RedirectStandardOutput, RedirectStandardError