我是靠谱客的博主 含蓄路灯,最近开发中收集的这篇文章主要介绍Delphi实现程序只运行一次并激活已打开的程序,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

unit wdRunOnce;

{*******************************************
 * brief: 让程序只运行一次
 * autor: linzhenqun
 * date: 2005-12-28
 * email: linzhengqun@163.com
 * blog: http://blog.csdn.net/linzhengqun
********************************************}

interface

(* 程序是否已经运行,如果运行则激活它 *)
function AppHasRun(AppHandle: THandle): Boolean;


implementation
uses
  Windows, Messages;

const
  MapFileName = '{CAF49BBB-AF40-4FDE-8757-51D5AEB5BBBF}';

type
  //共享内存
  PShareMem = ^TShareMem;
  TShareMem = record
    AppHandle: THandle;  //保存程序的句柄
  end;

var
  hMapFile: THandle;
  PSMem: PShareMem;

procedure CreateMapFile;
begin
  hMapFile := OpenFileMapping(FILE_MAP_ALL_ACCESS, False, PChar(MapFileName));
  if hMapFile = 0 then
  begin
    hMapFile := CreateFileMapping($FFFFFFFF, nil, PAGE_READWRITE, 0,
      SizeOf(TShareMem), MapFileName);
    PSMem := MapViewOfFile(hMapFile, FILE_MAP_WRITE or FILE_MAP_READ, 0, 0, 0);
    if PSMem = nil then
    begin
      CloseHandle(hMapFile);
      Exit;
    end;
    PSMem^.AppHandle := 0;
  end
  else begin
    PSMem := MapViewOfFile(hMapFile, FILE_MAP_WRITE or FILE_MAP_READ, 0, 0, 0);
    if PSMem = nil then
    begin
      CloseHandle(hMapFile);
    end
  end;
end;

procedure FreeMapFile;
begin
  UnMapViewOfFile(PSMem);
  CloseHandle(hMapFile);
end;

function AppHasRun(AppHandle: THandle): Boolean;
var
  TopWindow: HWnd;
begin
  Result := False;
  if PSMem <> nil then
  begin
    if PSMem^.AppHandle <> 0 then
    begin
      SendMessage(PSMem^.AppHandle, WM_SYSCOMMAND, SC_RESTORE, 0);
      TopWindow := GetLastActivePopup(PSMem^.AppHandle);
      if (TopWindow <> 0) and (TopWindow <> PSMem^.AppHandle) and
        IsWindowVisible(TopWindow) and IsWindowEnabled(TopWindow) then
        SetForegroundWindow(TopWindow);
      Result := True;
    end
    else
      PSMem^.AppHandle := AppHandle;
  end;
end;

initialization
  CreateMapFile;

finalization
  FreeMapFile;

end.
program Project1;

uses
  Forms,
  Unit1 in 'Unit1.pas' {Form1}
  wdRunOnce in 'wdRunOnce.pas',
  Unit2 in 'Unit2.pas' {Form2}

{$R *.res}

begin
  Application.Initialize;
  if not AppHasRun(Application.Handle) then
    Application.CreateForm(TForm1, Form1);
  Application.Run;
end.

特此感谢资料: http://blog.csdn.net/linzhengqun/article/details/564646

最后

以上就是含蓄路灯为你收集整理的Delphi实现程序只运行一次并激活已打开的程序的全部内容,希望文章能够帮你解决Delphi实现程序只运行一次并激活已打开的程序所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(55)

评论列表共有 0 条评论

立即
投稿
返回
顶部