2021年11月13日土曜日

Delphi10 など ShellExecute

 

参照:

https://www.greelane.com/ja/%e7%a7%91%e5%ad%a6%e6%8a%80%e8%a1%93%e6%95%b0%e5%ad%a6/%e3%82%b3%e3%83%b3%e3%83%94%e3%83%a5%e3%83%bc%e3%82%bf%e3%82%b5%e3%82%a4%e3%82%a8%e3%83%b3%e3%82%b9/execute-and-run-applications-1058462/

メモ帳を実行する

ShellApiを使用します。
...
ShellExecute(Handle、 'open'、
'c:\ Windows \ notepad.exe'、nil、nil、SW_SHOWNORMAL);

メモ帳でSomeText.txtを開く

ShellExecute(Handle、 'open'、
'c:\ windows \ notepad.exe'、
'c:\ SomeText.txt'、nil、SW_SHOWNORMAL);

「DelphiDownload」フォルダの内容を表示する

ShellExecute(Handle、 'open'、
'c:\ DelphiDownload'、nil、nil、SW_SHOWNORMAL);

拡張子に従ってファイルを実行する

ShellExecute(Handle、 'open'、
'c:\ MyDocuments \ Letter.doc'、nil、nil、SW_SHOWNORMAL);

拡張機能に関連付けられているアプリケーションを見つける方法は次のとおりです。

デフォルトのWebエクスプローラーでWebサイトまたは* .htmファイルを開く

ShellExecute(Handle、 'open'、
'http://delphi.about.com'、nil、nil、SW_SHOWNORMAL);

件名とメッセージ本文を記載したメールを送信する

var em_subject、em_body、em_mail:文字列; 
begin
em_subject:= 'これは件名です';
em_body:= 'メッセージ本文テキストはここにあります';

em_mail:= 'mailto:delphi@aboutguide.com?subject =' +
em_subject + '&body =' + em_body;

ShellExecute(Handle、 'open'、
PChar(em_mail)、nil、nil、SW_SHOWNORMAL);
終わり;

添付ファイル付きのメール送信する方法は次のとおりです。

プログラムを実行し、終了するまで待ちます

次の例では、ShellExecuteExAPI関数を使用しています。

// Windows Calculatorを実行し
、計算が終了すると//メッセージをポップアップします。
ShellApiを使用します。
...
var
SEInfo:TShellExecuteInfo;
ExitCode:DWORD;
ExecuteFile、ParamString、StartInString:文字列;
開始
EXECUTEFILEを:= 'C:\ WINDOWS \ CALC.EXE';

FillChar(SEInfo、SizeOf(SEInfo)、0);
SEInfo.cbSize:= SizeOf(TShellExecuteInfo);
SEInfoを使用してfMaskを開始し
ます:= SEE_MASK_NOCLOSEPROCESS;
Wnd:= Application.Handle;
lpFile:= PChar(ExecuteFile);
{
ParamStringには、
アプリケーションパラメータを含めることができます。
}
// lpParameters:= PChar(ParamString);
{
StartInStringは、
作業ディレクトリの名前。
省略した場合は、現在のディレクトリが使用されます。
}
// lpDirectory:= PChar(StartInString);
nShow:= SW_SHOWNORMAL;
終わり;
ShellExecuteEx(@SEInfo)の場合、Application.ProcessMessagesの
繰り返しを開始し
ます。
GetExitCodeProcess(SEInfo.hProcess、ExitCode);
(ExitCode <> STILL_ACTIVE)または
Application.Terminatedまで;
ShowMessage( '電卓が終了しました');
end
else ShowMessage( 'Calcの開始中にエラーが発生しました!');
終わり;

ShellExecute in Delphi – Launch external applications.

ShellExecute is Delphi Windows API function that is mostly used for launch external applications from our Delphi application. This function is linked to the ShellExecute Windows API function. The function returns an integer that corresponds to an error code which is very useful when we need to show some status if the function worked or not.

By using ShellExecute we can also do following operations....

  • Can print documents from within my program, without explicitly starting the application that created the document, such as: print a Word-document without starting Word.
  • Can open browser with a local HTML page
  • Can surf to a site i.e. open an external URL link from a Delphi application
  • Can send mails thorugh outlook
Syntax of Windows API function

HINSTANCE ShellExecute(
  _In_opt_        HWND hwnd,
  _In_opt_        LPCTSTR lpOperation,
  _In_              LPCTSTR lpFile,
  _In_opt_        LPCTSTR lpParameters,
  _In_opt_        LPCTSTR lpDirectory,
  _In_INT         nShowCmd
);

Parameters Details

_In_opt_  HWND hwnd,
A handle to the parent window used for displaying a UI or error messages. Ex - handle

_In_opt_  LPCTSTR lpOperation,
Operations to perform.
edit      = Launches an editor and opens the document for editing
explore = Explores a folder 
find      = Initiates a search beginning in the directory 
open     = Opens an item, file, folder, link
print     = Prints the file

_In_      LPCTSTR lpFile,
FileName, link URL to open and modify. EX - PChar(filename)

_In_opt_  LPCTSTR lpParameters
the parameters to be passed to the application delimited by space. Ex - '-c -i -v'

_In_opt_  LPCTSTR lpDirectory,
the default (working) directory for the action. 

_In_      INT nShowCmd
how an application is to be displayed when it is opened. 
SW_HIDE = Hides the window and activates another window
SW_MAXIMIZE  = Maximizes the specified window
SW_MINIMIZE = Minimizes the specified window and activates the next top-level window in the z-order
SW_RESTORE  = Activates and displays the window.
SW_SHOW  = Activates the window and displays it in its current size and position.
SW_SHOWDEFAULT  = Sets the show state based on the SW_ flag specified in the STARTUPINFO
SW_SHOWMAXIMIZED  = Activates the window and displays it as a maximized window.
SW_SHOWMINIMIZED  = Activates the window and displays it as a minimized window.
SW_SHOWMINNOACTIVE  = Displays the window as a minimized window. The active window remains active
SW_SHOWNA  = Displays the window in its current state. The active window remains active.
SW_SHOWNOACTIVATE  = Displays a window in its most recent size and position. The active window remains active.
SW_SHOWNORMAL  = Activates and displays a window. If the window is minimized or maximized, Windows restores it to its original size and position. 

Return Values from ShellExecute function

If the return value of ShellExecute is greater than 32, the application was executed successfully.
If its less than 33 then the function failed.
Here is a complete list of the possible return values of ShellExecute:
0 = The operating system is out of memory or resources.
2 = The specified file was not found
3 = The specified path was not found.
5 = Windows 95 only: The operating system denied access to the specified file
8 = Windows 95 only: There was not enough memory to complete the operation.
10 = Wrong Windows version
11 = The .EXE file is invalid (non-Win32 .EXE or error in .EXE image)
12 = Application was designed for a different operating system
13 = Application was designed for MS-DOS 4.0
15 = Attempt to load a real-mode program
16 = Attempt to load a second instance of an application with non-readonly data segments.
19 = Attempt to load a compressed application file.
20 = Dynamic-link library (DLL) file failure.
26 = A sharing violation occurred.
27 = The filename association is incomplete or invalid.
28 = The DDE transaction could not be completed because the request timed out.
29 = The DDE transaction failed.
30 = The DDE transaction could not be completed because other DDE transactions were being processed.
31 = There is no application associated with the given filename extension.
32 = Windows 95 only: The specified dynamic-link library was not found.

Example...

Procedure OpenMyURL(sUrl: string)
var
  iRes: Integer;
  sMsg: String;
begin
  // If the return value of ShellExecute is greater than 32, the application was executed successfully.
  // If its less than 33 then the function failed.
  try
    iRes := -1;
    sMsg := '';
    iRes := ShellExecute(Handle, 'open', Pchar(sUrl), '', '', SW_SHOWNORMAL);
    case iRes of
      0:
        sMsg := 'The operating system is out of memory or resources.';
      2:
        sMsg := 'The specified file was not found';
      3:
        sMsg := 'The specified path was not found.';
      5:
        sMsg := 'Windows 95 only: The operating system denied access to the specified file';
      8:
        sMsg := 'Windows 95 only: There was not enough memory to complete the operation.';
      10:
        sMsg := 'Wrong Windows version';
      11:
        sMsg := 'The .EXE file is invalid (non-Win32 .EXE or error in .EXE image)';
      12:
        sMsg := 'Application was designed for a different operating system';
      13:
        sMsg := 'Application was designed for MS-DOS 4.0';
      15:
        sMsg := 'Attempt to load a real-mode program';
      16:
        sMsg := 'Attempt to load a second instance of an application with non-readonly data segments.';
      19:
        sMsg := 'Attempt to load a compressed application file.'
      20
        sMsg := 'Dynamic-link library (DLL) file failure.';
      26:
        sMsg := 'A sharing violation occurred.';
      27:
        sMsg := 'The filename association is incomplete or invalid.';
      28:
        sMsg := 'The DDE transaction could not be completed because the request timed out.';
      29:
        sMsg := 'The DDE transaction failed.';
      30:
        sMsg := 'The DDE transaction could not be completed because other DDE transactions were being processed.';
      31:
        sMsg := 'There is no application associated with the given extension.';
      32:
        sMsg := 'Windows 95 only: The specified dynamic-link library was not found.';
    end;
    if sMsg <> EmptyStr then
      MessageDlg(sMsg, mtError, [mbOK], 0);
  except
    on E: Exception do
      MessageDlg(E.Message, mtError, [mbOK], 0);
  end;
end;

Note*
In order to use the function, you first need to add the ShellApi to your uses clause, like : 

uses 
   ShellApi;

Use of ShellExecute with Example

Start an application:
ShellExecute(Handle, 'open', PChar('c:\test\app.exe'), nil, nil, SW_SHOW); 

Start NotePad and load a file (the system "knows" the location of NotePad.exe, therefore we don't have to specify the full path):
ShellExecute(Handle, 'open', PChar('notepad'), PChar('c:\test\readme.txt'), nil, SW_SHOW);

Print a document:
ShellExecute(Handle, 'print', PChar('c:\test\test.doc'), nil, nil, SW_SHOW);  

Note: probably you will see the window of Word open very briefly, but it is closed automatically.

Open an HTML page, local or remote:
ShellExecute(Handle, 'open', PChar('http://www.google.com/'), nil, nil, SW_SHOW);

You can do the previuos trick with any type of registered data-file, e.g. open a Text file:
ShellExecute(Handle, 'open', PChar('c:\test\readme.txt'), nil, nil, SW_SHOW);

HTML Help File:
ShellExecute(Handle, 'open', PChar('c:\windows\help\calc.chm'), nil, nil, SW_SHOW);

Explore a folder with Windows Explorer:
ShellExecute(Handle, 'explore', PChar('c:\windows)', nil, nil, SW_SHOW);

Run a DOS command and return immediately:
ShellExecute(Handle, 'open', PChar('command.com'), PChar('/c copy file1.txt file2.txt'), nil, SW_SHOW);

Run a DOS command and keep the DOS-window open ("stay in DOS"):
ShellExecute(Handle, 'open', PChar('command.com'), PChar('/k dir'), nil, SW_SHOW);

Run an executable and show it:
filename := 'c:\program.exe';
ShellExecute(handle,'open',PChar(filename), '','',SW_SHOWNORMAL);

Run an executable and minimize it:
filename := 'c:\program.exe';
ShellExecute(handle,'open',PChar(filename), '','',SW_MINIMIZE);

Run an executable and maximize it:
filename := 'c:\program.exe';
ShellExecute(handle,'open',PChar(filename), '','',SW_MAXIMIZE);

Run an executable and hide it:
filename := 'c:\program.exe';
ShellExecute(handle,'open',PChar(filename), '','',SW_HIDE);

Run an executable with parameters:
filename := 'c:\program.exe';
parameters := '-c -i -v';
ShellExecute(handle,'open',PChar(filename), PChar(parameters), '', SW_SHOWNORMAL);

Send a mail with attachment
ShellExecute(Self.Handle,
             nil,
             'mailto:' +
             'jiten.g.s001@gmail.com' +
             '?Subject=Test Message Subject' +
             '&Body=Test Message Body' +
             '&Attach="c:\Mail\attachment.txt"',
             nil,
             nil,
             SW_NORMAL);

0 件のコメント:

コメントを投稿