pjhayward's Pascal Tutorial |
|
pjhayward.net Home Got a question? Tutorial Home Preparation Lesson One - Sample Program Lesson Two - Program Structure Lesson Three - Data Types and Constants Lesson Four - Variables Lesson Five - Text I/O Lesson Six - Subroutines Lesson Seven - Conditional Statements Lesson Eight - Arrays Lesson Nine - Loops Lesson Ten - Units | How do you open a program from Pascal? Well, I'm going to limit this to Windows for now. Here's a unit I wrote to handle this exact question:
unit APIUtils;
interface
uses Windows, ShellAPI;
procedure ShellOpen(path:PChar); //useful for starting default browser, etc.
procedure StartProcess(path:PChar);
function EndTask(hWnd:HWND;fShutDown:BOOL;fForce:BOOL): BOOL; stdcall;
implementation
{$EXTERNALSYM EndTask}
function EndTask(hWnd:HWND;fShutDown:BOOL;fForce:BOOL): BOOL; stdcall; external 'user32.dll' name 'EndTask';
procedure ShellOpen(path:PChar); //useful for starting default browser, etc.
var
Handle:HWND;
begin
Handle:=0;
ShellExecute(Handle,'open',path,nil,nil,SW_ShowNormal);
end;
procedure StartProcess(path:PChar);
var
StartupInfo:TStartupInfo;
ProcessInfo:TProcessInformation;
begin
Fillchar(StartupInfo,SizeOf(StartupInfo),0);
Fillchar(ProcessInfo,SizeOf(ProcessInfo),0);
StartupInfo.cb:=sizeof(StartupInfo);
CreateProcess(nil,path,nil,nil,false,0,nil,nil,StartupInfo,ProcessInfo);
end;
end.
As you can see, I've got two procedures for starting programs, and one for closing them. This unit is part of my Desktop Planner application, and so has been customized for that purpose. The ShellExecute and CreateProcess API functions are the core of these utilities, and are documented on the Microsoft website. One of the gotchas to watch for is that these use pchar values instead of pascal strings. That's because they're C functions, and only understand PChar. You should be able to do a simple typecast to get these to work - i.e. ShellOpen((pchar)mydocpath); The ShellOpen procedure uses the Windows shell to open a program OR a document. That means you can use this procedure on 'c:\documents and settings\me\My Documents\somedoc.doc', and it'll work, as long as the .doc extension has something associated with it. You can also pass in programs, URLs, or anything else you could put in the Run dialog off the start menu. The StartProcess procedure is only for starting programs. It has the benefit of NOT using the Windows shell, which generally means it's faster and uses less memory. I use ShellOpen for documents and URLs, and StartProcess for programs. Back to Question/Answer list |