views:

283

answers:

2

Hi,

I have a console application (SRMan.exe) which derives from System.Windows.Forms.Form. I could be able to hide the form while exe is running. code i used is here

    this.Opacity = 0;
    this.Size = new Size(0, 0);
    this.Location = new Point(-100, -100);
    this.Visible = false;

Aslo, configured the form properties ShowIcon and ShowInTaskbar to false.

but i could not able to get the Window handle of the of that running process.code i used is here

Process[] process1 = Process.GetProcessesByName("SRMan");
IntPtr pt = process1[0].MainWindowHandle;

Any help is appreciated!

Thanks,
Karim.

A: 

Any reason why you can't just grab the handle from the form's Handle property? Anything that derives from the Control class, which Forms do, will have a Handle property.

Why are you resorting to grabbing it from the process?

Erich Mirabal
I would be starting the process(SRMan.exe) from another process and I have to post the messages to that running process. So i need to use Process[] process1 = Process.GetProcessesByName("SRMan");IntPtr pt = process1[0].MainWindowHandle;
as Sk93 points out, try using process1[0].WaitForInputIdle(); That has worked for me in the past as well.
Erich Mirabal
+2  A: 

Hi Karim,

At what point are you calling:

Process[] process1 = Process.GetProcessesByName("SRMan");
IntPtr pt = process1[0].MainWindowHandle;

pt will be returned as zero or "MainWindowHandle" may throw an exception if the main window handle hasn't been created yet.

Try changing your code to:

Process[] process1 = Process.GetProcessesByName("SRMan");
process1[0].WaitForInputIdle();
IntPtr pt = process1[0].MainWindowHandle;

as this will force your code to wait until the process is fully loaded. (MSDN article)

As an example, the following code works fine for me:

 private Thread thd;

 private void Form1_Load(object sender, EventArgs e)
 {            
     thd = new Thread(new ThreadStart(GetHandle));
     thd.Start();
     this.Opacity = 0;
     this.Size = new Size(0, 0);
     this.Location = new Point(-100, -100);
     this.Visible = false;
 }

 private void GetHandle()
 {
     Process[] process1 = Process.GetProcessesByName("WindowsFormsApplication12.vshost");
     process1[0].WaitForInputIdle();
     IntPtr pt = process1[0].MainWindowHandle;
     MessageBox.Show(pt.ToString());
 }
Sk93
Just read you're calling Process.GetProcessByName() from a seperate app.I was getting the same issue as you until I added the WaitForInputIdle() method and it worked for me :)
Sk93
+1. The `process1[0].WaitForInputIdle();` is the important part to remember.
Erich Mirabal