tags:

views:

274

answers:

3

I have simple win application(writen using .net C#) that needs to be started from cmd.exe, and then write to that console, but problem is that i need process id from that cmd.exe process. I can get all running process,

Process[] procList = Process.GetProcessesByName("cmd");

but how to find my? :)

Maybe to read input, and check is "ApplicationName.exe" writen inside, or to get curently active cmd.exe window? But with what function?

A: 

Even if you find "yours" cmd, how are you going to write into it?

There is a better way to achieve what you describe. Just compile your project as "Console Application", but have it create a WinForms window anyway. Yes, it is possible, nothing stops you from it. Then you would be able to write to the console using your System.Console class, no magic required.

Fyodor Soikin
A: 

Its not problem to write, using AttachConsole and using WriteConsoleInput i allready tested all, my program is command line anyway, but problem is that i need to hide console if parameter is set up, but if i compile as console application, and in main function use ShowWindow to hide console, console appears for milisecund and then disapere, and i cant overide that, or is there any way to do that?

So that's why i compile my console app as windows, and allocate new console if "-verbose" parameter is set up, and everything is running fine if i double click on program, but if i try to run program from command line application, then my programm allocate another cmd windows, and i need to find my parent cmd windows and connect there using AttachConsole, but problem is to find that window :).

So? ;)

DoDo
Actually, it would be better if you edited your question instead of posting an answer (people do not expect to find additional information about the question in answer.
RaphaelSP
sry, didnt think about that, i will not repeat that again.
DoDo
A: 

The following code creates a WQL event query to detect a new process, waits for a new process to start and then displays the information about the process:

WqlEventQuery query = new WqlEventQuery("__InstanceCreationEvent", new TimeSpan(0, 0, 1), "TargetInstance isa \"Win32_Process\"");
ManagementEventWatcher watcher = new ManagementEventWatcher(query);
ManagementBaseObject e = watcher.WaitForNextEvent();
Console.WriteLine("Process {0} has been created, path is: {1}", 
((ManagementBaseObject)e["TargetInstance"])["Name"],
((ManagementBaseObject)e["TargetInstance"])["ExecutablePath"]);
watcher.Stop();

I think you may find a solution to your problem by examining this WMI code sample. Hope it helps.

Seventh Element