LoginSignup
6
0

子プログラム停止

Last updated at Posted at 2023-12-24

本投稿はDelphi Advent Calendar 2023 24日目 の記事です。

はじめに

以前1本のExeにすることが多かったが最近は複数のプログラムに分割して作成することが多くなった。
メニューExeから各機能のプログラムを起動する仕組みとなるのだが、メニューを閉じたときに起動したプログラムが閉じる仕組みを、レジストリを使って同期をとっていたのだが、Mutexでもできると思いつき、そのテストプログラムを作成してみた。

仕組み

メニューは、起動時に、Mutexを生成します。
サブプログラム側では、このMutexが生きているかをタイマーで定期的にチェックし、生きていればそのまま。生きていなければ、終了します。

メインソース

dprファイルをこんな感じに。

const
  Mutexname = '____MainMenu';
var
  hMutex: THandle;  // Mutex用ハンドル
begin
  Application.Initialize;
  Application.MainFormOnTaskbar := True;
  hMutex := OpenMutex(MUTEX_ALL_ACCESS, False, Mutexname);
  if hMutex = 0 then
  begin
    hMutex := CreateMutex(nil, False, Mutexname);
    Application.CreateForm(TForm1, Form1);
    Application.Run;
  end;
  ReleaseMutex(hMutex);
  CloseHandle(hMutex);
end.

サブソース

タイマーイベント中に下記のように、Mutexをチェックする処理を

var
  hMutex: THandle;  // Mutex用ハンドル
const
  Mutexname = '____MainMenu';
begin
  hMutex := OpenMutex(MUTEX_ALL_ACCESS, False, Mutexname);
  if hMutex = 0 then
  begin
    Close;
  end;
  ReleaseMutex(hMutex);
  CloseHandle(hMutex);
end;

おわりに

https://delphi-dev.sakura.ne.jp/FileBox/Delphi_Advent_Calendar_2023_24.zip
で、ソースをダウンロードできるようにしました。

6
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
0