今天图老师小编给大家展示的是后台调用外部程序的完美实现(Delphi),精心挑选的内容希望大家多多支持、多多分享,喜欢就赶紧get哦!
【 tulaoshi.com - 编程语言 】
最近在做的一个软件,其中有一部分功能需要调用其它的软件来完成,而那个软件只有可执行文件,根本没有源代码,幸好,我要做的事不难,只需要在我的程序启动后,将那个软件打开,在需要的时候,对其中的一个文本矿设置一些文字,再点击一个按钮就可以了。 The SetThreadDesktop function will fail if the calling thread has any windows or hooks on its current desktop (unless the hDesktop parameter is a handle to the current desktop).
哦,原来需要切换Desktop的线程中不能有任何UI方面的东西,而我是在程序的主线程中调用该方法的,当然会失败拉,知道了这点就好办了,我只需要用一个“干净”的线程,让它绑定到新的Desktop上,再让它用FindWindow()方法找到我要找的WindowHandle,不就可以了吗,于是,这一步就需要借助一个线程了,线程的代码如下:
TFindWindowThread = class(TThread)
private
FDesktop:THandle;
FWindowHandle:THandle;
protected
procedure Execute();override;
public
constructor Create(ACreateSuspended:Boolean;const ADesktop:THandle);reintroduce;
property WindowHandle:THandle read FWindowHandle;
end;
{ TFindWindowThread }
procedure TFindWindowThread.Execute();
var
I:Integer;
begin
//make the current thread find window on the new desktop!
if not SetThreadDesktop(FDesktop) then begin
exit;
end;
for I:=0 to 60 do begin //wait 30 seconds for open the main window
FWindowHandle:=FindWindow(nil,PChar('WindowCaption'));
if FWindowHandle0 then begin
break;
end;
Sleep(500);
end;
end;
constructor TFindWindowThread.Create(ACreateSuspended:Boolean;const ADesktop:THandle);
begin
inherited Create(ACreateSuspended);
FDesktop:=ADesktop;
end;
而主程序中的代码变成这样:
FindWindowThread:=TFindWindowThread.Create(false,FDesktop);
try
FindWindowThread.WaitFor;
FMainWindowHandle:=FindWindowThread.WindowHandle;
finally
FindWindowThread.Free;
end;
if FMainWindowHandle=0 then begin
MessageBox(Application.Handle,'Error when init voice (6).',PChar(Application.Title),MB_ICONWARNING);
exit;
end;
呵呵,成功,这样果然可以顺利的找到窗口Handle了。
4)最后,再用这个主窗口Handle,找出里面的EditBox的Handle,如这样:
FEditWindow:=FindWindowEx(FMainWindowHandle,0,PChar('Edit'),nil);
我在这里指定了这个文本框的ClassName,这个名称可以用Spy++得到。
初始化的工作就到此结束了,如果顺利,程序就真正在后台被运行了起来。那么功能调用呢,还是和一般的做法一样:
if (FMainWindowHandle=0) or (FEditWindow=0) then begin
exit;
end;
SendMessage(FEditWindow,WM_SETTEXT,0,LongInt(@AText[1]));
SendMessage(FMainWindowHandle,WM_COMMAND,$8012,$0);
其中$8012这个数字,也是用Spy++来得到的资源ID。
最后,别忘了关闭程序,以及释放虚拟Desktop:
if FProceInfo.hProcess0 then begin
TerminateProcess(FProceInfo.hProcess,0);
end;
if FDesktop0 then begin
CloseDesktop(FDesktop);
end;
好了,这样就几乎完美的实现了一个后台调用程序的功能,它对最终客户来说将是完全透明的,客户根本感觉不到后台还有另一个程序在工作。是不是很爽啊,这样别人的很多程序我们都可以直接拿来用了(当然了,得在遵守版权的基础上才行拉)。
有任何改进意见,或交流,可以Mail至:tonyki[at]citiz.net
来源:http://www.tulaoshi.com/n/20160219/1622283.html
看过《后台调用外部程序的完美实现(Delphi)》的人还看了以下文章 更多>>