C# can I add the command prompt control to my app - c#

Title says it. I know I can use Process or ProcessStartInfo to run arguments, but I mean actually adding a command prompt control to my app (because I use it very often and it'd be convenient if it was already built-in.
Is there any way to do this other than coding a custom control? If not I can live with it, but it would definitely help.

Something like this (not tested):
ProccessInfo pi = new ProccessInfo("cmd.exe");
pi.RedirectStandardError=true;
pi.RedirectStandardInput=true;
pi.RedirectStandardOutput=true;
Process cmd = Process.Start(pi);
cmd.StandardInput.WriteLine("Dir");
textBox1.Text = cmd.StandardOutput.ReadToEnd();
Watch out for deadlocks, those method can be blocking!
You can also use this solution from codeproject.com: http://www.codeproject.com/KB/miscctrl/commandprompt.aspx

See this question and related. Also this source code for example.
You can start a console near your win app's window which you will control and can output some data or get input from a user.

What is the problem with doing Console.ReadLine()/Console.WriteLine() in a loop? It is the most efficient way and you have fully control over what you are doing.

Related

c# detect an open web browser

I am writing a program that searches certain web pages before closing. I would like my program to open a NEW WINDOW using the DEFAULT BROWSER. I can have my program focus the newest window instance, and then it will close that instance once it is done.
I have been staring at WebBrowser.Navigate and System.Diagnostics.Process.Start(target) all day but I cant find the sweet spot with either of them.
WebBrowser.Navigate always opens IE, I have been looking in the API and can't find a way to change the program used. Does anyone else see something that I dont? Is there a way to change the application used?
System.Diagnostics.Process.Start(target) opens in a new tab, not a new window like navigate does. However none of the overloaded functions from the API have a way of saying "create a new instance or window".
this is my issue, they both have pieces that I want, but I cant figure out how to get the pieces I need for either one.
I would be extremely grateful for you help. I have been looking for hours now and I can seem to come to a solution.
code sample for Jester:
Process defaultbrowser = new Process();
defaultbrowser.StartInfo.CreateNoWindow = true;
defaultbrowser = Process.Start(target);
int waitTime = Convert.ToInt32(numericUpDown2.Value);
System.Threading.Thread.Sleep(waitTime*1000);
defaultbrowser.CloseMainWindow();
defaultbrowser.Close();
furthermore my Close() function is causing a runtime error that says;
System.NullReferenceException: Object reference not set to an instance
of an object.
which seems silly because too me the above code makes me think that my defaultbrowser is an instance of a process, which is then supposed to be able to call the non-static function "close()".
ok If I got your problem right you are looking for a way to open a web page in the "default" browser.
That can be done by simply make a new process like:
Process.Start("http://google.com");
If you would like to control witch browser gets used you can do it by passing the web address to the browser's exe file as a parameter:
System.Diagnostics.Process.Start("PATH to exe", "Command Line Arguments");
To start the process in the new window pass a ProcessInfo object to the Process.Start
And set the CreateNoWindow
more info on that
Hey To check if it's loaded wherever, do:
if(browser.ReadyState == WebBrowserReadyState.Complete) {
// It's Open!
}
You should use System.Diagnostics.Process like that:
Process Chrome = new Process(); //Create the process
Chrome.StartInfo.FileName = #"C:\Program Files\Google\Chrome\Application\chrome.exe"; // Needs to be full path
Chrome.StartInfo.Arguments = ""; // If you have any arguments
Chrome.Start();

Using C# code to simulate textbox filling and button pressing

I'm working on a C# program which automates tasks. For example, my program opens an external application (specifically mstsc.exe) and uses the application. I want to write code which fills textboxes with certain values and presses certain buttons. What is the right and most elegant way to implement such operations in a C# 4 code?
if your special target is mstsc.exe use its parameters:
mstsc.exe [<Connection File>] [/v:<Server>[:<Port>]] [/admin] [/f] [/w:<Width> /h:<Height>] [/public] [/span]
mstsc.exe /edit <Connection File>
mstsc.exe /migrate
else Windows Input Simulator (C# SendInput Wrapper - Simulate Keyboard and Mouse) is a reliable and open-source library on CodePlex for your issue.
my solution for this problem, it´s solved with "SendKeys":
var Proc = new System.Diagnostics.Process();
Proc.StartInfo.FileName = "C:\\Windows\\System32\\mstsc.exe";
//Proc.StartInfo.Arguments = "/v:" + "PCwg01"; normaly
Proc.Start();
System.Threading.Thread.Sleep(100);
SendKeys.Send("PCwg01"); //name or IP adress
SendKeys.Send("\r");
i hope it will help ;)

Call default browser with URL and set a target

I don't know if there is a mechanism to do this: normally one would simply call process start with a URL as the string parameter - has anyone any knowlege or sugestions as to how to add a target?
Google has been singularly unhelpful or else my queries have been a tad useless.
As in the behavior you get with :
link in a new window
Try selenium and WebDriver for C#.
What is the harm in launching the default browser ?
you may do this but what if firefox is not available ! !
ProcessStartInfo proc1 = new ProcessStartInfo("firefox.exe");
proc1.Arguments = "http://www.w3schools.com/tags/att_a_target.asp";
//"http://stackoverflow.com";
Process.Start(proc1);

Changing environment variables of the calling process

This one seems trivial but the answer has eluded me for a few days now.
I have a Windows batch file, that calls a C# program to do an extra verification that cannot be done in a batch file. After the verification is complete I need to return a status and a string back to the calling shell.
Now the return value is trivial and my C# console app simply sets a return value (exit code if you will). And I thought the string will also be a piece of cake. I attempted to define a new shell variable using the:
Environment.SetEnvironmentVariable("ERR", "Some text");
This call should (and does) define a shell variable within the current process - that is the very C# process that created the variable. The value is lost as soon as the C# app terminates and the shell that created the C# app knows nothing about the variable. So... A call with no particular use... At all... Unless perhaps if I created a child process from the C3 app, perhaps it would inherit my variables.
The EnvironmentVariableTarget.Machine and EnvironmentVariableTarget.User targets for the SetEnvironmentVariable call don't solve the problem either, as only a newly created process will get these new values from the registry.
So the only working solution I can think of is:
write to stdout
write to a file
encode extra meaning into the return value
The first two are a bit ugly and the last one has its limitations and problems.
Any other ideas (how to set a shell variable in the parent process)? Maybe such shell variable modifications are a security concern (think PATH)...
Thank-you for your time.
I had the same problem as Ryan and the only thing that came to my mind as a work-around was to write a batch in error out to set the variable and to call it from the batch.
ConsoleApplication1.exe:
'put some sensible code here
'put result in variable myResult
Dim myResult As String = Guid.NewGuid().ToString("D").ToUpperInvariant()
Console.WriteLine("Normal output from the consonle app")
Console.Error.WriteLine("#ECHO OFF")
Console.Error.WriteLine("SET zzzResult={0}", myResult)
Test.cmd (the calling batch):
#ECHO OFF
:Jump to folder of batch file
PUSHD %~d0%~p0
:Define a temp file
SET zzzTempFile=%TEMP%\TMP%Random%.CMD
:Call .NET console app
ConsoleApplication1.exe 2>%zzzTempFile%
:Call the generated batch file
CALL %zzzTempFile%
:Clean up temp file
DEL %zzzTempFile%
:Clean up variable
SET zzzTempFile=
:Do something with the result
ECHO Yeah, we finally got it!
ECHO:
ECHO The value is "%zzzResult%".
ECHO:
:Clean up result variable
SET zzzResult=
:Go back to original folder
POPD
That should do the trick. And yes, I do know this is an old post and Ryan is solving other issues by now, but there might be still somebody else out there having the same problem...
What you are asking is to be able to arbitrarily write to the memory space of a running process. For good reason, this is not possible without SeDebugPrivilege.
Any of the three solutions you list will work. Stdout is the standard way to communicate with a batch script.
By the way, you're writing a Windows batch file. I'm pretty sure the ship has already sailed on "a bit ugly".
If you want to put a value of some output into a variable in the batch you can use the following construct:
FOR /F "usebackq tokens=4 delims=\[\] " %i IN (`ver`) DO set VERSION=%i
ECHO %VERSION%
Output on my OS:
6.1.7601
'usebackq' means we are using back quotes which gives the ability to use a fileset in the command quoted with double quotes. You may not need this. 'tokens' means the index in the resulting string array to select (it can be a range M-N). If you need to skip lines use 'skip=X'). 'delims' are the string separators to use (like string-Split() in .Net).
You will put your console app instead of 'ver' and adapt the delimiters and tokens to match your specific output. If you have more variables to fill you will need to make the if a bit more complex but that should make a good start.
My BAT is a bit rusty, but I think it's possible to retrieve the 'exit' code from processes you've run externally, perhaps via %ERRORLEVEL%. If that's the case, make sure to exit your program via
Environment.Exit(123); // where 123 = error code
You can't add any messages, so you'll have to do that in the .bat file.
If this isn't the case, stdout is probably the best way.
After stumbling on this myself as well recently, I came up with this approach. What I did is run the bat file using the Process class, i.e.
// Spawn your process as you normally would... but also have it dump the environment varaibles
Process process = new Process();
process.StartInfo.FileName = mybatfile.bat;
process.StartInfo.Arguments = #"&&set>>envirodump.txt";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = false;
process.Start();
string output = process.StandardOutput.ReadToEnd();
process.WaitForExit();
// Read the environment variable lines into a string array
string[] envirolines = File.ReadAllLines("envirodump.txt");
File.Delete("envirodump.txt");
// Now simply set the environment variables in the parent process
foreach(string line in a)
{
string var = line.Split('=')[0];
string val = line.Split('=')[1];
Environment.SetEnvironmentVariable(var, val);
}
This seems to have worked for me. It's not the cleanest approach, but will work in a bind. :)

I need to open several VLC clients in order to "monitor" the stream they're receiving

I want to be able to specify how many clients do I want opened, and be able to manually switch between the windows after they're opened- meaning "streaming in background" (if such a thing is possible? ) won't do here.
I need to specify different inputs for the different clients as well.
Additionally -and this is the part I'm totally clueless about as it's VLC-specific - I need the clients to be logging some info re:the stream they're receiving, so as to be able to determine that it has been received completely etc -such as frame rate/total frames' number or similar.
I'd appreciate helpful suggestions for
running the instances+ controlling
them
getting info about
the stream
Language-wise - I know Java, some C#, and wouldn't mind learning some new language for this purpose if it's a better solution .
Thanks!
Depending on your version of VLC, you may need to enable an option to run multiple instances. See here: http://wiki.videolan.org/How_to_play_multiple_instances_of_VLC
It does sound like a 'run windows processes in a loop' thing, which you could do several ways.
You could make a windows batch file (.bat):
"C:\path\to\vlc.exe" -vvv "http://www.whatever.com/mystream.mms"
"C:\path\to\vlc.exe" -vvv "http://www.whatever.com/mystream2.mms"
"C:\path\to\vlc.exe" -vvv "C:\music\whatever.mp3"
Or you could use a real programming language and perhaps open a variable number of instances... C# for example:
using System.Diagnostics;
...
foreach (string stream in streamList) {
Process myProc = new Process();
string myCmd = #"C:\path\to\vlc.exe";
string myArgs = "-vvv \"" + stream + "\"";
ProcessStartInfo myStart = new ProcessStartInfo(myCmd, myArgs);
myStart.UseShellExecute = false;
myProc.StartInfo = myStart;
myProc.Start();
}
See this page for a full list of VLC command line options: http://www.videolan.org/doc/vlc-user-guide/en/ch04.html
Hope this helps.
You'll either need to run several processes (as above) or hook somehow into libvlc and instruct it to start up several players.
A good demo of this is the python wrapper to libvlc--I think--it shows how to sample to know where the stream is--however I've never tried it with multiple things running at the same time but I think it would work.
Another option might be something like http://wiki.videolan.org/Mosaic

Categories

Resources