My Blog

Hosting Process in Windows Forms Application

by lupok on lunedì 4 febbraio 2013 12:37

Occorre creare un progetto di tipo Windows Forms Application ed aggiungere un nuovo User Control:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
 
namespace WindowsFormsProcessHosting
{
   public partial class HostControl : UserControl
   {
      [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
      static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
 
      [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
      private static extern bool MoveWindow(IntPtr hwnd, int x, int y, int cx, int cy, bool repaint);
 
      private IntPtr m_clientHandle = IntPtr.Zero;
 
      public HostControl()
      {
         InitializeComponent();
      }
 
      public void Host(String application)
      {
         System.Diagnostics.Process process = System.Diagnostics.Process.Start(application);
 
         process.WaitForInputIdle();
 
         m_clientHandle = process.MainWindowHandle;
 
         SetParent(m_clientHandle, Handle);
 
         MoveWindow(m_clientHandle, 0, 0, this.Width, this.Height, true);
      }
 
      protected override void OnResize(EventArgs e)
      {
         base.OnResize(e);
 
         if (m_clientHandle != IntPtr.Zero)
            MoveWindow(m_clientHandle, 0, 0, this.Width, this.Height, true);
      }
   }
}
Dopo aver creato in controllo che ospiterà l'applicazione occorre: 

1) aggiungere il controllo alla finestra principale nella posizione desiderata,
2) inserire nella finestra principale un bottone al cui click verrà creato il processo da ospitare.

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
 
namespace WindowsFormsProcessHosting
{
   public partial class Form1 : Form
   {
 
      public Form1()
      {
         InitializeComponent();
      }
 
      private void btnHost_Click(object sender, EventArgs e)
      {
         hostControl.Host("notepad");
      }
 
   }
}
WindowsFormsProcessHosting.zip

Blogs Parent Separator My Blog
Author
lupok

My Blog

Tags