以下是網絡上編寫的代碼供參考:
unit?frmTestEmbedApp;interface
uses
Windows,?Messages,?SysUtils,?Variants,?Classes,?Graphics,?Controls,?Forms, Dialogs,?ExtCtrls;type
TForm1?=?class(TForm)pnlApp:?TPanel;
procedure?FormCreate(Sender:?TObject);
procedure?FormClose(Sender:?TObject;?var?Action:?TCloseAction);
procedure?FormResize(Sender:?TObject);
private{?Private?declarations?}
public{Public?declarations?} end;var
Form1:?TForm1; hWin:?HWND?=?0;implementation
{$R?*.dfm}
type
//?存儲窗體信息 PProcessWindow?=?^TProcessWindow; TProcessWindow?=?recordProcessID:?Cardinal;
FoundWindow:?hWnd;
end;//?窗體枚舉函數
function?EnumWindowsProc(Wnd:?HWND;?ProcWndInfo:?PProcessWindow):?BOOL;?stdcall;
var
WndProcessID:?Cardinal;begin
GetWindowThreadProcessId(Wnd,?@WndProcessID); if?WndProcessID?=?ProcWndInfo^.ProcessID?then beginProcWndInfo^.FoundWindow?:=?Wnd;
Result?:=?False;?//已找到,故停止?EnumWindows
end elseResult?:=?True;//繼續查找
end;
//由?ProcessID?查找窗體?Handle
function?GetProcessWindow(ProcessID:?Cardinal):HWND;
var
ProcWndInfo:?TProcessWindow;begin
ProcWndInfo.ProcessID?:=?ProcessID; ProcWndInfo.FoundWindow?:=?0; EnumWindows(@EnumWindowsProc,?Integer(@ProcWndInfo));?//?查找窗體 Result?:=?ProcWndInfo.FoundWindow;end;
//?在?Panel?上內嵌運行程序
function?RunAppInPanel(const?AppFileName:?string;?ParentHandle:?HWND;?var?WinHandle:
HWND):?Boolean;var
si:?STARTUPINFO; pi:?TProcessInformation;begin
Result?:=?False; //?啟動進程 FillChar(si,?SizeOf(si),?0); si.cb?:=?SizeOf(si); si.wShowWindow?:=?SW_SHOW; if?not?CreateProcess(nil,?PChar(AppFileName),?nil,?nil,?true,CREATE_NEW_CONSOLE?or?NORMAL_PRIORITY_CLASS,?nil,?nil,?si,?pi)?then?Exit;
//?等待進程啟動 WaitForInputIdle(pi.hProcess,?10000); //?取得進程的?Handle WinHandle?:=?GetProcessWindow(pi.dwProcessID); if?WinHandle?>?0?then?begin//?設定父窗體
Windows.SetParent(WinHandle,?ParentHandle);
//?設定窗體位置
SetWindowPos(WinHandle,?0,?0,?0,?0,?0,?SWP_NOSIZE?or?SWP_NOZORDER);
//?去掉標題欄
SetWindowLong(WinHandle,?GWL_STYLE,?GetWindowLong(WinHandle,?GWL_STYLE)
and?(not?WS_CAPTION)?and?(not?WS_BORDER)?and?(not?WS_THICKFRAME));Result?:=?True;
end; //?釋放?Handle CloseHandle(pi.hProcess); CloseHandle(pi.hThread);end;
procedure?TForm1.FormClose(Sender:?TObject;?var?Action:?TCloseAction);
begin
//?退出時向內嵌程序發關閉消息 if?hWin?>?0?then?PostMessage(hWin,?WM_CLOSE,?0,?0);end;
procedure?TForm1.FormCreate(Sender:?TObject);
const
App?=?'calc.exe';begin
pnlApp.Align?:=?alClient; //?啟動內嵌程序 if?not?RunAppInPanel(App,?pnlApp.Handle,?hWin)?thenShowMessage('App?not?found');
end;
procedure?TForm1.FormResize(Sender:?TObject);
begin
//?保持內嵌程序充滿?pnlApp if?hWin?<>?0?thenMoveWindow(hWin,?0,?0,?pnlApp.ClientWidth,?pnlApp.ClientHeight,?True);
end;
end.