Click here to Skip to main content
Click here to Skip to main content

Hosting EXE Applications in a WinForm project

By , 21 Dec 2004
 

Sample Image

Introduction

Though not a common task, recently I needed to take an existing executable application and embed it into an application I was building. Oddly enough, I did not need any interaction between my application and the existing EXE. As it ends up, this is not a difficult thing to do. To make it even easier, I created a custom C# control that allows you to specify the name of an executable you want embedded into your application. The control takes care of all the rest.

How does it work

In design time, the user can specify the name of the executable to embed. When the control is created in runtime, it launches the application as follows:

Process p = null; 
try 
{
  // Start the process 
  p = System.Diagnostics.Process.Start(this.exeName); 

  // Wait for process to be created and enter idle condition 
  p.WaitForInputIdle(); 

  // Get the main handle
  appWin = p.MainWindowHandle; 
} 
catch (Exception ex) 
{ 
  MessageBox.Show(this, ex.Message, "Error"); 
}

After launching, the code must then set the parent of the executable's main window to the control handle. It does this as follows:

// Put it into this form
SetParent(appWin, this.Handle);

// Remove border and whatnot
SetWindowLong(appWin, GWL_STYLE, WS_VISIBLE);

// Move the window to overlay it on this window
MoveWindow(appWin, 0, 0, this.Width, this.Height, true);

Any time the control is resized, it must also resize the executable window. To do so, it does this in the Resize function:

protected override void OnResize(EventArgs e)
{
  if (this.appWin != IntPtr.Zero)
  {
    MoveWindow(appWin, 0, 0, this.Width, this.Height, true);
  }
  base.OnResize (e);
}

Lastly, when the control is destroyed, it should shut down the executable. To do so, it does the following:

protected override void OnHandleDestroyed(EventArgs e)
{
  // Stop the application
  if (appWin != IntPtr.Zero)
  {

    // Post a colse message
    PostMessage(appWin, WM_CLOSE, 0, 0);

    // Delay for it to get the message
    System.Threading.Thread.Sleep(1000);

    // Clear internal handle
    appWin = IntPtr.Zero;

  }

  base.OnHandleDestroyed (e);
}

History

  • 12-20-2004: Released.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Jay Nelson
Web Developer
United States United States
Member
I have been developing software professionaly since 1991 writing software in Automation and Manufacturing environments. For 14 years I worked for companies that built custom robotic automated equipment for the semiconductor, telecommunications, and other industies. Presently, I work for a medical device manufacturer developing applications for the compact framework.
 
My undergraduate degrees are in Mathematics and Philosopy. My graduate degree is in Management Information Systems. I am MCSD certified in Visual C++ 6.0 and MCSD.NET certified in C#.
 
I enjoy triathlons and reading.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralFor those who can't get it working for any application other than notepadmemberChristopher Sippel9 Apr '13 - 7:33 
Here is a link with a solution that worked for me:
 
http://stackoverflow.com/a/5965992/1097080
 
I was getting it working, but only for Notepad.exe, and the solution was to use the While loop in the above link.
Questiontoopstrip disabledmemberMember 902164117 Feb '13 - 23:27 
Hi, i have tried to host an application inside a web panel of a form and all works except that thebuttons and textbox are not invoking the methods corresponding to its events
It works fine if i dont bind it with panel
 
Some one could help me ???
plzzz

Questionwindows 7 problemmemberMember 930102825 Jul '12 - 12:26 
i tryed with windows 7 and dont works.. Some1 have a solution?
AnswerRe: windows 7 problemmemberRaRi200323 Nov '12 - 2:46 
Try this one.
Window Tabifier[^]
QuestionHosting External Exe Application in a WPF Window. [modified]membersukesh.gudikandulla27 May '12 - 6:35 
Please help me, how to open External exe application in a WPF Window. Thanks...
 
Below is the code...sample right now..i am using.. let me know what i need to modify in the code below..to work for external exe to launch in WPF window. This is opening application in separately not in WPF Window.
 
namespace WpfApplication_Blend
{
///
/// Interaction logic for Window1.xaml
///

public partial class Window1 : Window
{
public IntPtr MainWindowHandle { get; set; }
 

[DllImport("user32.dll", SetLastError = true)]
private static extern long SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
 

//[DllImport("user32.dll", SetLastError = true)]
//private static extern int GetWindowLong(IntPtr hWnd, int nIndex);
 
public Window1()
{
InitializeComponent();
 
try
{
//External exe inside WPF Window
System.Windows.Forms.Panel _pnlSched = new System.Windows.Forms.Panel();
 
WindowsFormsHost windowsFormsHost1 = new WindowsFormsHost();
 
windowsFormsHost1.Child = _pnlSched;
 
_Grid.Children.Add(windowsFormsHost1);
 
ProcessStartInfo psi = new ProcessStartInfo(@"C:\Program Files\Atwin\Atwin2k2.exe");
 
psi.WindowStyle = ProcessWindowStyle.Normal;
 
Process PR = Process.Start(psi);
 
PR.WaitForInputIdle(); // true if the associated process has reached an idle state.
SetParent(PR.MainWindowHandle, _pnlSched.Handle); // loading exe to the wpf window.
 
}
catch (Exception ex)
{
//Nothing...
}
}
 

 
}
}

modified 27 May '12 - 13:12.

QuestionIt doesn't work in window 7memberdhojonline3 Apr '12 - 2:44 
I tried running the exes it does not work in WIndows 7.
Need different way of handling it.
 
Any suggestion will be much appreciated.
AnswerRe: It doesn't work in window 7memberk3v1n5215 May '12 - 2:19 
Same problem for me.
Notepad is running fine in the panel. iexplore, excel, acrobat reader ... open as a popup.
GeneralRe: It doesn't work in window 7memberMember 899490321 May '12 - 3:40 
I have put a "this post based code" that works, answered in the post:
can't start programe that have login window. caixrz 21:56 11 Apr '07
 
Hope it helps.
QuestionHow to stop exe flashing up or appearing in taskbarmemberJamesA_Dev26 Jan '12 - 1:24 
Some programs can take a second or two to start.
When this happens, you get the program flash up and an entry for it in the taskbar.
It then gets re-parented properly.
 
Any ideas to stop this?
(Win7 with sleep fix).
QuestionMenus are disabledmemberdelfo8 Aug '11 - 22:07 
Hi, i have tried to host an application inside a windows forms on Win7 (with the bug fix corrected) and all works except that the menus and toolbar don't works.
Some one could help me ???
Thanks in advance
Stefano
GeneralMy vote of 4memberyanghe11173 May '11 - 4:16 
nice
GeneralMy vote of 5memberYusuf18 Jan '11 - 9:35 
Simple and Elegant 5
QuestionAdvice neededmemberHollyY18 Nov '10 - 12:57 
I know this is an old article, but I was wondering if/how you could implement something like this but reversed. That is run an application inside a web page instead of a browser inside of an application.
 
Thanks
GeneralWin7 and Vista Incompatablemembercs_can3 Apr '10 - 3:28 
Instead of using System.Threading.Thread.Sleep(1000), I fixed the error by following code:
 
while( p.MainWindowHandle == IntPtr.Zero || !IsWindowVisible(p.MainWindowHandle))
{
System.Threading.Thread.Sleep(10);
p.Refresh();
}
p.WaitForInputIdle();
 
You have to declare the IsWindowVisible within the same class:
 
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool IsWindowVisible(IntPtr hWnd);
 
Hope the above help.
QuestionPowerPoint Viewer Does Not seem to workmemberMember 265354228 Dec '09 - 21:47 
I am working with VC# 2008. Powerpoint viewer application does not seem to work with this.
Furthermore, I tried retrieving the parent handle after SetParent using GetParent.
The parent handle is different from this.Handle.
Does this mean that it parent control functions have been disabled on the exe or am I misiing something ?
 
Abi

GeneralAnother problemmemberil172316 Nov '09 - 5:36 
I finnaly run the application. just commented //PostMessage(appWin, WM_CLOSE, 0, 0); and // SetWindowLong(appWin, GWL_STYLE, WS_VISIBLE); in appcontrol.
 
Now I have other problem, I cannot start the application then a form is already opened. so if i put all working code to Form_Load function it doesn't work. It works only in InitializeComponent() function.
 
what should i do ?
 
thnx
GeneralProblemmemberil172316 Nov '09 - 4:59 
what should i fix if i recieve folowing error ? it happens when this string executing "this.Controls.Add(this.applicationControl1);"
 
PInvokeStackImbalance was detected
A call to PInvoke function 'AppControl!AppControl.ApplicationControl::SetWindowLong' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature.
GeneralRe: ProblemmemberElbe Alves Miranda24 Feb '11 - 3:24 
Replace:
[DllImport ("user32.dll", EntryPoint = "SetWindowLong", SetLastError = true)]
private static extern long SetWindowLong (IntPtr hwnd, int nIndex, long dwNewLong
);
by:
[DllImport ("user32.dll", EntryPoint = "SetWindowLong", SetLastError = true)]
private static extern int SetWindowLong (IntPtr hwnd, int nIndex, int dwNewLong);

GeneralReally great, works perfectly after bug fix - thank you very much!memberBlasterwurm10 Nov '09 - 4:39 
With the following "bug fix" your code works perfectly, Jay!
 
"Bug fix" to solve problem that the external application is opened in a new window instead of being hosted/integrated in Form1:
http://www.codeproject.com/Messages/3169714/Re-Vista-incompatibility.aspx
 
Furthermore you can set the property "Enabled" of applicationControl1 (included in Form1) to False to dissallow any interaction with the hosted application - that's exactly what I wanted.
 
Thank you so much Smile | :)
GeneralRe: Really great, works perfectly after bug fix - thank you very much!memberAtchyuta Rao9 Dec '09 - 20:29 
Before the application is launched in the control, i could see the application in separate window for a second...how can i avoid this?
GeneralRe: Really great, works perfectly after bug fix - thank you very much!membercs_can3 Apr '10 - 5:41 
Try using my routine instead of using sleep(1000)
GeneralApplication dosen't workmembertreuveni26 Sep '09 - 9:37 
Hello,
 
Can some please help me with this code?
The explorer dosen't open if the application,
What i'm doing wrong???
GeneralNice Article... But one clarification required ... Running the Code..it;s launching the custom control and IE .. separately [modified]memberNikkiee28 May '09 - 7:00 
Hi,
 
Good Shot....nice article.....
 
But running the Code, for my self I found it;s launching the custom control and IE .. separately
I tried to run the code and as a result .. running WindowsApplication1 application ..it is not launching the IE inside the user control..
But what is happing is the UI form having nothing launching first .. then the IE is launching separately outside the user control...not inside the control.
 
Have anyone noticed that.. But as per my understanding the IE shud launch inside the form as it is a Custom control.
 

Jay, can you please help me why it is happing like this ..Do I need to do something else.
I tried with VS 2005 and VS 2008 and release and debug mode of dlls...getting the same results.
Actually treating the example as a sample, I want to create one user control which would launch the Adobe Photoshop.
 
modified on Thursday, May 28, 2009 1:11 PM

GeneralRe: Nice Article... But one clarification required ... Running the Code..it;s launching the custom control and IE .. separately [modified]memberBlasterwurm10 Nov '09 - 2:18 
Problem is solved here:
http://www.codeproject.com/KB/miscctrl/AppControl.aspx?msg=3169714#xx3169714xx
 
modified on Tuesday, November 10, 2009 9:36 AM

GeneralRe: Nice Article... But one clarification required ... Running the Code..it;s launching the custom control and IE .. separately [modified]memberbencodeproject2515 Mar '11 - 11:33 
http://www.codeproject.com/KB/miscctrl/AppControl.aspx?msg=3169714#xx3169714xx
the above link doesn't have the solution for the said above problem.still it is pointing out old source not the rectified source.
 
could you please provide us the exact link where the said above problem is rectified

modified on Wednesday, March 16, 2011 9:48 AM

GeneralRe: Nice Article... But one clarification required ... Running the Code..it;s launching the custom control and IE .. separately [modified]membersukesh.gudikandulla27 May '12 - 7:43 
I am also getting same issue, IE is opening separtely not inside the Usercontrol form.
 
Please provide your inputs to resolve this issue.
 
Thanks,
Sukesh
GeneralScrollingmemberWallbert Elicot22 Apr '09 - 1:39 
Hi.. Thanks for creating this user control.. Im just wondering how do i set the autoscroll property for this control?
 
After ive created the control, im setting the autoscroll property to true but when i tried launching it, it does not autoscroll:
 
e.g.
 
AppControl.ApplicationControl newApp = new AppControl.ApplicationControl();
newApp.AutoScroll = true;
 
does anyone know how to add autoscroll to this user control?
QuestionAll good for Microsoft Programs like notepad and Excel but what about others like winamp?membernoka036 Apr '09 - 20:31 
Hi I'm attempting to write my own version of carPC software using other peoples compiled .exe files.
Your project is great for making a tabbed notepad editor and other apps the like.
 
Do you know of any way to add winamp and make it work properly inside your control when i tried it it adds the "controls" part but the play list is completely separate as is the Eq.
 

Thanks in advance
-noka03
AnswerRe: All good for Microsoft Programs like notepad and Excel but what about others like winamp? [modified]memberBlasterwurm10 Nov '09 - 2:20 
Instead of "iexplore" you should write "C:/Program Files/Winamp/winamp.exe"
 
modified on Tuesday, November 10, 2009 9:35 AM

QuestionThe EXE application is a separate window, not hosted by the control!memberNotGood27 Feb '09 - 5:07 
The code to get the main handle ( appWin = p.MainWindowHandle; ) sometimes returns 0. That means the code (p.WaitForInputIdle(); ) doesn’t work well. In this case, the EXE application is a separate window, not hosted by the control. Any suggestion for this?
QuestionRe: The EXE application is a separate window, not hosted by the control!memberpcm_it14 Mar '09 - 1:45 
same problems i also face any soln you find out?
AnswerRe: The EXE application is a separate window, not hosted by the control!membermbaocha6 May '09 - 16:43 
I saw that your post was about 3 months ago and so i was wondering if you latered figured out a solution to that. I'm encountering same problem. Did you later get these to work?
 
_______________________________________________________________________
Cheap Affordable Web Hosting | Windows Linux PHP ASPX MYSQL Website Hosting | Best Web Design & Development Company
GeneralRe: The EXE application is a separate window, not hosted by the control!memberBlasterwurm10 Nov '09 - 3:37 
Problem is solved here:
http://www.codeproject.com/KB/miscctrl/AppControl.aspx?msg=3169714#xx3169714xx
QuestionAwesome!!!memberMember 440744029 Jan '09 - 5:30 
This is sweet! Thanks for sharing it.
 
Here is one question I have:
I'm using this to open Textpad.exe on a panel (actually multiple instances of Textpad on separate panels -- one instance per panel) and everything works great (opening files, saving files, etc.) except in the case where I make changes to a file and don't save the changes before closing the form. Normally, Textpad asks the user if they want to save the changes if changes have been made. When running it through the C# app, the save changes message pops up and quickly disappears, and then it crashes ("SEND ERROR REPORT TO MICROSOFT" or "DON'T SEND") when I close the form. Everything closes just fine if there are no changes to save. Does anyone know what I can do to let the user answer the save changes question before the form actually closes?
QuestionRe: Awesome!!!memberKrishna01 Valluri5 Mar '10 - 0:20 
I have the same requirement, did anyone manage to figure this out....
AnswerRe: Awesome!!!membercs_can3 Apr '10 - 5:54 
I have invested a day to solve this but nearly success. I capture the FormClosing event after get the MainWindowHandle:
 

attachForm = FindForm();
attachForm.FormClosing += new FormClosingEventHandler(FormClosing);
 

void FormClosing(object sender, FormClosingEventArgs e)
{
if (this.appWin != IntPtr.Zero)
{
p.CloseMainWindow();
e.Cancel = true;
}
}

 
And also raise another form close event by capturing Process.Exited event:
 

p.EnableRaisingEvents = true;
p.Exited += new EventHandler(p_Exited);
 
void p_Exited(object sender, EventArgs e)
{
appWin = IntPtr.Zero;
attachForm.Close();
}
 

 
But when it executes attachForm.Close(), it fails ....
 
And I think more and more, if you want such "Save Changes" function, this object should be inherited from a form control, instead of panel, right?
 
It is rather easy to modify the code to a form control.
 
Hope this can help.
GeneralWorks great but...memberMember 447052825 Jan '09 - 8:31 
I've used this sample to create a Windows Home Server Add-In that hosts another exe file. Works fint except for one thing. The application in questions apparently uses a timer to refresh it's content. When running standalone there is no problem, but when running inside a WinForm using the code from this article the applications "flickers" once a second. I assume this is some kind of refresh thread/timer doing something.
 
Is there any double buffering or other technique I can use that might help?
QuestionRewritten with bug fix?memberThord Johansson9 Dec '08 - 22:07 
Could the control be rewritten so that it doesnt try to run the process from within the Designer and only during runtime?
Generalnice articlememberMember 237557729 Oct '08 - 9:59 
you mentiond it is possible to communicate to a method in the application hosted within control. any insight into that, can you shed?
GeneralWow... ExcellentmemberMrWolfy14 Sep '08 - 8:53 
Hi!
 
You know it's like you read my mind, Excellent control, Excellent Article, Just When I needed it!
 
Thanks!
 
MrWolfy Big Grin | :-D
GeneralCan't load sample code.membersupermankelly31 Jul '08 - 3:30 
hey Im new to VS C# and tried loading the demo into VS C# Express 2008 but it doen't run?
QuestionQuestions about really cool componentmemberjbyrneiu22 Jul '08 - 16:05 
This is exactly what I was looking for.
 
Is there a way to keep the app in "exename" from starting in design mode? Not a problem, per se, but I only want to start the app at runtime.
 
Will this work in Vista?
 
Thanks for your great component. It has made my app much easier to use!
 
John Byrne Smile | :)
GeneralVista incompatibilitymemberAndrei Pana23 Mar '08 - 12:14 
Does not work on Vista. The application is opened in a separate window. Otherwise, cool article Smile | :)
GeneralRe: Vista incompatibilitymemberEnquiren4 Jul '08 - 20:32 
This technique does work in Vista, but not IE7.
GeneralRe: Vista incompatibilitymemberEnquiren4 Jul '08 - 20:38 
Also not working with Sidebar (or explorer as one might imagine from IE7 incompatibility).
AnswerRe: Vista incompatibilitymemberAndre Wells22 Aug '09 - 4:04 
Yeah, same problem but I have a solution:
 
I was stepping through the control's code (running on IE7 and Vista sp1) and
noticed that it works when placing a breakpoint at
 
appWin = p.MainWindowHandle;
 
(Line 147, i think) and stepping through execution.
 
I'm unsure of the exact cause, but it looks like it needs a second or so of delay
to get the proper handle when running with Vista and IE7.
 
Modifying the parameter for WaitForInputIdle() doesn't seem to help.
I modified the control to the following:
 
// Wait for process to be created and enter idle condition
System.Threading.Thread.Sleep(1000);
 
Dirty, i know, but it works Smile | :)
GeneralRe: Vista incompatibilitymemberAtchyuta Rao9 Dec '09 - 20:03 
Should we replace the WaitForInputIdle() with the sleep(1000) command ? I did that and still it opens the IE in separate window!!!
GeneralRe: Vista incompatibilitymemberMember 869768711 Apr '12 - 6:15 
No, put it right before appwin=p.MainWindowHandle;
 
// Get the main handle
System.Threading.Thread.Sleep(1000);
appWin = p.MainWindowHandle;

GeneralRe: Vista incompatibilitymemberShulha Yahya8 Jun '12 - 10:51 
i've tried this and change the value from 1000 to 30000 on "System.Threading.Thread.Sleep(1000);" but doesn't effect anything
GeneralRe: Vista incompatibilitymemberShulha Yahya8 Jun '12 - 11:15 
ahaa, its work.
I just forgot to change the AppControl reference to the new one that has been modified.
 
Thanks

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130516.1 | Last Updated 21 Dec 2004
Article Copyright 2004 by Jay Nelson
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid