The so-called "kidnapping" is to embed the forms of other Win32 programs into our managed WinForm. many java and Delphi versions and WPF versions have been used on the Internet. I will add C # here.
Define the required Win32 API
[DllImport ("user32.dll")]
Private static extern int SetParent (IntPtr hWndChild, IntPtr hWndParent );
[DllImport ("user32.dll")]
Private static extern bool ShowWindowAsync (IntPtr hWnd, int nCmdShow );
[DllImport ("user32.dll", SetLastError = true)]
Private static extern bool PostMessage (IntPtr hWnd, uint Msg, int wParam, int lParam );
[DllImport ("user32.dll", EntryPoint = "SetWindowPos")]
Private static extern bool SetWindowPos (IntPtr hWnd, int hWndInsertAfter,
Int X, int Y, int cx, int cy, uint uFlags );
[DllImport ("user32.dll")]
Private static extern int SendMessage (IntPtr hWnd, uint Msg, int wParam, int lParam );
[DllImport ("user32.dll", SetLastError = true, CharSet = CharSet. Auto)]
Private static extern uint SetWindowLong (IntPtr hwnd, int nIndex, uint newLong );
[DllImport ("user32.dll", SetLastError = true, CharSet = CharSet. Auto)]
Private static extern uint GetWindowLong (IntPtr hwnd, int nIndex );
[DllImport ("user32.dll", CharSet = CharSet. Auto)]
Private static public extern bool ShowWindow (IntPtr hWnd, short State );
Private const int HWND_TOP = 0x0;
Private const int WM_COMMAND = 0x0112;
Private const int WM_QT_PAINT = 0xC2DC;
Private const int WM_PAINT = 0x000F;
Private const int WM_SIZE = 0x0005;
Private const int SWP_FRAMECHANGED = 0x0020;
Start the program we need to kidnap Private void Form1_Load (object sender, EventArgs e)
{
P = new Process ();
// The program to be started
P. StartInfo. FileName = @ "c: \ windows \ system32 \ notepad.exe ";
// Minimize the program at startup for the sake of beauty
P. StartInfo. WindowStyle = ProcessWindowStyle. Minimized;
// Start
P. Start ();
// Wait. Otherwise, the handler of the Startup Program has not been created and cannot be controlled.
Thread. Sleep (1000 );
// Programs to maximize startup
ShowWindow (p. main1_whandle, (short) ShowWindowStyles. SW_MAXIMIZE );
// Set the parent window of the kidnapped Program
SetParent (p. main1_whandle, this. Handle );
// Change the size
ResizeControl ();
}
// Control the position and size of the embedded Program
Private void ResizeControl ()
{
SendMessage (p. main1_whandle, WM_COMMAND, WM_PAINT, 0 );
PostMessage (p. main1_whandle, WM_QT_PAINT, 0, 0 );
SetWindowPos (
P. main1_whandle,
HWND_TOP,
0-5, // set the offset to cover the menu of the original window
0-41,
(Int) this. Width,
(Int) this. Height + 36,
SWP_FRAMECHANGED );
SendMessage (p. main1_whandle, WM_COMMAND, WM_SIZE, 0 );
}
Private void Form1_SizeChanged (object sender, EventArgs e)
{
ResizeControl ();
}
It should be noted that the ResizeControl () method is very important, otherwise it will not achieve our expected results.