请问如何检测一个指定的进程已存在于内存中(急......)。 (30分)

  • 主题发起人 主题发起人 p_jz
  • 开始时间 开始时间
P

p_jz

Unregistered / Unconfirmed
GUEST, unregistred user!
我在用TWordApplication组件对Word文档进行操作时,
很容易出现一些不明白的错误发生,错误大多发生在内存
中有两个WinWord进程存在时。所以我想在用WordApplication
时,先判断是否已存在WinWord进程,并想办法重新利用它,或
释放它。望大家指点。偌大家有更优的方法自然再好不过了。
 
//hubdog 的 delphi葵花宝典
//防止运行多个例程
var
hMutex : Thandle;
WaitResult : word;
BroadcastList : DWORD;
begin
MessageID := RegisterWindowMessage('Check For Choice Previous Inst');
// register a message to use later on
hMutex := createMutex(nil,false,pchar('App_Choice')); // grab a mutex
handle
WaitResult := WaitForSingleObject(hMutex,10); // wait to see
if we can have exclusive use of the mutex
if ( waitResult = WAIT_TIMEOUT ) then // if we can't then broadcast
the message to make the owner of the mutex respond

{ request that the running application takes focus }
begin
BroadcastList := BSM_APPLICATIONS;
BroadcastSystemMessage(
BSF_POSTMESSAGE,@BroadcastList,MessageID,0,0); //32 bit - broadcast the
message to all apps - only a prev inst will hear it.
end
else
begin
{ do the normal stuff}
Application.Title := 'Choice Organics Purchase & Sales System';
Application.CreateForm(TMainForm, MainForm);
Application.Run;
ReleaseMutex(hMutex); // release the mutex as a politeness

end;
CloseHandle(hMutex); // close the mutex handle
end.

This goes in the MainForm

procedure Tmainform.OnAppMessage(var Msg : TMsg ; Var Handled : Boolean);
begin
{ If it's the special message then focus on this window}
if Msg.Message = MessageID then // if we get the broadcast message from an
another instance of this app that is trying to start up
begin
show;
WindowState := wsMaximized;
BringToFront;
SetFocus;
Handled := true;

end;
end;

//And this goes in the TMainForm.FormCreate ;-

Application.OnMessage:= OnAppMessage;
 
我觉得你可以用
FindWindow(0, '窗口名');
来获得是否有已经存在的word文档
 
To: Pingbaoshi
对不起,可能我没有把问题说清楚。我是在使用WordAppliction来关闭
或打开Word的工具条时经常出错的。这时并不存在某一Word文档窗口。可是
在进程列表中却常显示有两个或多个WinWord.exe进程。我一受尽了这种错
误的折磨,望多加指点。
 
TWordApplication组件没用过,
不过,如果你知道你要运行的程序的窗口的名字的话,
可以用myhandle:=FindWindow(0, '窗口名');
来获得它的句柄
句柄大于0,说明已经存在一个进程,
调用terminateprocess()终止它,
再重新运行一个新的
 
接受答案了.
 
后退
顶部