|

楼主 |
发表于 2012-5-10 12:49:08
|
显示全部楼层
以下方式在Lazarus下也可以实现互斥:- program project1;
- {$mode objfpc}{$H+}
- uses
- {$IFDEF UNIX}{$IFDEF UseCThreads}
- cthreads,
- {$ENDIF}{$ENDIF}
- Interfaces, // this includes the LCL widgetset
- Forms, Unit1,
- windows
- { you can add units after this };
- {$R *.res}
- const
- MemFileSize = 1024;
- MemFileName = 'one_inst_TST';
- var
- MemHnd, MainFormHnd : HWND; // DWord;
- FFileView: Pointer;
- begin
- MemHnd := CreateFileMapping(HWND($FFFFFFFF),nil, PAGE_READWRITE, 0, MemFileSize, MemFileName);
- if GetLastError<>ERROR_ALREADY_EXISTS then begin
- FFileView:=nil;
- Application.Initialize;
- Application.CreateForm(TForm1, Form1);
- MainFormHnd:= Form1.Handle;
- // 写MainForm的处理文件
- FFileView := MapViewOfFile(MemHnd,FILE_MAP_ALL_ACCESS,0,0,0);
- if FFileView <> nil then begin
- CopyMemory( FFileView, @MainFormHnd, 4);
- UnmapViewOfFile(FFileView);
- end;
- Application.CreateForm(TForm1, Form1);
- Application.Run;
- end
- else begin
- // 从以前的实例中创建的文件阅读MainForm的句柄
- FFileView := MapViewOfFile(MemHnd,FILE_MAP_READ,0,0,0);
- CopyMemory( @MainFormHnd, FFileView, 4);
- SetForegroundWindow(MainFormHnd); // 激活以前
- end;
- CloseHandle(MemHnd);
- end.
复制代码 |
|