啟動外部程式

2022-08-17 15:54:21 字數 2179 閱讀 6342

啟動外部程式我們可以使用函式winexec、shellexecute和shellexecuteex。我推薦大家使用函式shellexecute,因為它既靈活,又簡單。看看下面的例子,用法就清楚了:

*: 啟動乙個程式

shellexecute(handle,"open",(lpcstr)"d:\\模擬程式.exe",null,null,sw_show);

* 啟動記事本 (因為記事本在系統路徑下,所以不必寫完整的路徑名了):

shellexecute(handle, "open", (lpcstr)"notepad",null, null, sw_show);

* 啟動記事本並載入乙個純文字檔案:

shellexecute(handle, "open", (lpcstr)"notepad",(lpcstr)"c:\\test\\readme.txt", null, sw_show);

* 使用記事本開啟乙個純文字檔案 (請確定*.txt檔案被關聯到記事本):

shellexecute(handle, "open", (lpcstr)"c:\\test\\readme.txt"),null, null, sw_show);

* 使用預設瀏覽器開啟**:

shellexecute(handle, "open", (lpcstr)"",null, null, sw_show);

* 列印乙個檔案:

shellexecute(handle, "print", (lpcstr)"c:/test/readme.txt",null, null, sw_show);

* 用windows explorer開啟乙個資料夾:

shellexecute(handle, "explore", (lpcstr)"c:/windows",null, null, sw_show);

* 執行乙個dos命令並立即返回:

shellexecute(handle, "open", (lpcstr)"command.com",(lpcstr)"\\c copy file1.txt file2.txt", null, sw_show);

* 執行乙個dos命令並保持dos視窗開啟 ("stay in dos"):

shellexecute(handle, "open", (lpcstr)"command.com",(lpcstr)"\\k dir", null, sw_show);

shellexecute函式原型及引數含義如下:

hinstance shellexecute(hwnd hwnd, lpctstr lpoperation, lpctstr lpfile, lpctstr lpparameters,  lpctstr lpdirectory, int nshowcmd);
●lpoperation:用於指定要進行的操作。其中「open」操作表示執行由filename引數指定的程式,或開啟由filename引數指定的檔案或資料夾;「print」操作表示列印由filename引數指定的檔案;「explore」操作表示瀏覽由filename引數指定的資料夾。當引數設為nil時,表示執行預設操作「open」。     

●lpfilename:用於指定要開啟的檔名、要執行的程式檔名或要瀏覽的資料夾名。     

●lpparameters:若filename引數是乙個可執行程式,則此引數指定命令列引數,否則此引數應為nil或pchar(0)。     

●lpdirectory:用於指定預設目錄。     

●lpshowcmd:若filename引數是乙個可執行程式,則此引數指定程式視窗的初始顯示方式,否則此引數應設定為0。 

返回值:

#include #include 

#include

#include

int main( void

)

else

printf(

"getlasterror: %d\n

", getlasterror());

system(

"pause");

return1;

}

當「d:\\test.log」檔案不存在是,執行結果如下:

這裡若函式執行錯誤, getlasterror()不一定能捕獲到錯誤**,例如當「d:\\tese.log」檔案存在,將記事本"notepad.exe"命名為其他名字時:

另外兩個函式的返回值就不列出了。

2、特殊用法

Delphi啟動外部程式

無論是用vc還是用delphi,啟動外部程式,呼叫的都是相同的系統中的api函式,如下delphi 所示 登入按鈕 procedure tform1.label loginclick sender tobject begin end delphi啟動其它程式函式 begin 使用winexec也可以...

Unity啟動外部程式(Process)

啟動外部程式時 直接使用process.start 來啟動外部程式,引數 需要啟動的外部程式所在檔案位置 關閉外部程式時 使用 process.kill 來關閉外部程式 private string exepath void start void ongui if gui.button new re...

delphi啟動外部程式執行結束

一 為什麼要啟動外部程式 二 預備知識 啟動外部程式我們可以使用函式winexec shellexecute和shellexecuteex。我推薦大家使用函式shellexecute,因為它既靈活,又簡單。看看下面的例子,用法就清楚了 啟動乙個程式 nil,nil,sw show 啟動記事本 因為記...