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();
Related
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);
I have a c# program which open *.postfix file.
If a user runs a (.lnk)shortcut which points to my type of file, my program will open the target.
So, how could my program know it is started by a (.lnk)shortcut (and get it's file path)?
In some circumstances,i need to replace the .lnk file.
Thanks!
Edited
First, thanks to guys who answered my question.
By following #Anders answer, i find out my problem lays here.
I made some changes to windows registry, so browser knows to throw customized protocol string to certain program.
some thing like this..
[InternetShortcut]
URL=myProtocol://abcdefg.....
That's maybe why i lost lpTitle. :(
I'm going to try this way:
Whenever my program invoked, of course fed with %1, program checks current opened explorer(Window), and try to get it's current path with IWebBrowserApp. With that path and desktop of course, scan and analyze *.lnk to determine which one to replace.
I think this will probably work, but not be sure. I will try.
continued
In native code you can call GetStartupInfo, if the STARTF_TITLEISLINKNAME bit is set in STARTUPINFO.dwFlags then the path to the .lnk is in STARTUPINFO.lpTitle. I don't know if there is a .NET way to get this info, you probably have to P/Invoke...
You don't. There's no way to do it. End of story.
So this has been brought to my attention due to a recent downvote. There's an accepted answer showing an idea that gets the path to the launching shortcut most of the time. However my answer is to the whole. OP wants the link to the shortcut so he can change it. That is what can't be done most of the time.
Most likely case is the shortcut file exists in the start menu but is unwritable. However other cases involve the shortcut coming from another launching application that didn't even read it from a disk but from a database (I've seen a lot of corporate level restricted application launch tools). I also have a program that launches programs from shortcuts not via IShellLink but by parsing the .lnk file (because it must not start COM for reasons) and launching the program contained. It doesn't pass STARTF_TITLEISLINKNAME because it's passing an actual title.
If you're using Visual Studio Setup Project to build an installer and do the file type association, you should follow these instructions http://www.dreamincode.net/forums/topic/58005-file-associations-in-visual-studio/
Open up your solution in Visual studio.
Add a Setup Project to your solution by file , add project,New project, Setup & Deployment projects,Setup project
Right-click on your setup project in the "Solution Explorer" window,Select view,then select file types.
you'll see the "file types" window displayed in Visual studio.At the top of the window will be "File types on target machine"
Right-click on "File types on target machine".the menu will pop up with Add "file type" Click on this.
you'll see "New document Type#1" added,and "&open"underneath it.
The "new document type#1" can be anything you want - change it to something descriptive.although the user never sees this,never use something common- be as unique as possible,Because you can overlay current file associations without even realizing it.For example,you might think"pngfile" might be a useful name- but using that will now send all"*.png" files to your application,instead of to an image viewer.A good practice maybe "YourCompantName.Filetype",where your company name is your name of your company's name, and "Filetype" is a descriptive text of your file.
In the "properties" window for your new type,you will need to change a few properties.:
Command:Change to the application that you want to run.If you click on the "..." and you will proberly want to locate and use the "primary Output..." File
Description: This is the description of the file type(if it doesn't describe it's self"
Extensions:This your list of extensions for you chosen Program.Separate each one with a ","
Icon:This will associate the icon with your file type,This shows up in the window explorer.
Now we move to that "&open ".This is an action that is available if your right-click on the file.The default action("&Open" is currently set as the default) is what happens when you double click on the file.Right click on your "New document type#1" to add actions,but for the moment,lets define our "&open" action
Click on "&Open".You will see in the properties window "Name","Arguments","Verbs". Verb is hidden from the user,but is the key that is stored in the registry.Leave it same as the name,But without the "&".The default for"Arguments" is "%1",Which means to pass the full path and filename to your application.You can add other stuff here as well,if you need to pass flags to your application to do special stuff.All this infomaton is getting passed to your application on the command line,so you'll need to be familiar with the "Environment.CommandLine" object.
If you need to set a different action as your default,just right click on the action and "set as default"
Basically, you'll pass the file path as an argument to your program. Then if it's a console application or Windows Forms , you should check the arguments in Program.Main
static void Main(string[] args)
{
//if file association done with Arguments %1 as per forum post above
//you file path should be in args[0]
string filePath = null;
if(args != null && args.Length > 0)
filePath = args[0];
}
For a WPF application you'll need to handle that in the StartUp event for your Application
void App_Startup(object sender, StartupEventArgs e)
{
string filePath = null;
if ((e.Args != null) && (e.Args.Length > 0))
{
filePath = e.Args[0];
}
}
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. :)
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.
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