2017-02-11 36 views
0

我想在運行我的代碼之後啓動計算機中的.exe程序,並且在程序打開後仍然執行一些操作,但是我一直在如何打開它。如何在c中執行外部程序

#include <stdio.h> 
#include <stdlib.h> 
#include <time.h> 
//#define _WIN32_WINNT 0x0500 
#include <windows.h> 

int main() { 
    POINT mouse; 
    //HWND hWnd = GetConsoleWindow(); 
    //ShowWindow(hWnd, SW_MINIMIZE); 
    //ShowWindow(hWnd, SW_HIDE); 
    // how to open program ? 
    system("start C:\Riot Games\League of Legends\LeagueClient.exe"); 

    while (true) { 
     GetCursorPos(&mouse); 
     int x = mouse.x; 
     int y = mouse.y; 
     SetCursorPos(x + rand() % 40 - 20, y + rand() % 40 - 20); 
     printf("x = %d ", mouse.x); 
     printf("y = %d\n", mouse.y); 
     Sleep(1); 
    } 
} 

由於兩個原因,系統函數不適用於我;它暫停代碼,直到應用程序退出,並且當我嘗試運行代碼時,它說他找不到C:Riot。

+0

'system()'函數等待執行的命令完成。在Linux或Mac上,您可以「fork()」或運行在後臺啓動外部可執行文件的命令。但是Windows沒有'fork()',我也不確定它是否具有後臺進程。您將需要Windows API的適當功能。 –

+0

哦,我明白了,謝謝。我會盡力找到它。 –

回答

0

這幾個問題是字符串"start C:\Riot Games\League of Legends\LeagueClient.exe"

首先,\字符用於轉義字符,這意味着輸入的字符如果直接插入到字符串中則意味着其他字符。例如,要將"寫入字符串中,應該使用\",因爲"本身就意味着它是字符串的結尾。同樣,\n意味着換行符,因爲您不能直接在字符串中寫入換行符。在這裏,\RC:\Riot Games意味着你正在逃避字符R這並不意味着什麼。編譯器將\R解釋爲簡單的R(對於\L也是如此),因此將字符串"start C:\Riot Games\League of Legends\LeagueClient.exe"轉換爲"start C:Riot GamesLeague of LegendsLeagueClient.exe"。要逃避\字符,請使用\\。到目前爲止,字符串應該是system("start C:\\Riot Games\\League of Legends\\LeagueClient.exe")

該字符串還存在另一個問題,就是命令行中的空間通常意味着您在空間之前指定參數的空間之前運行程序。這通常用於通過程序打開文件。爲了簡單起見,"start C:\\Riot Games\\League of Legends\\LeagueClient.exe"表示您想要運行程序C:\Riot並使其打開文件Games\League of Legends\LeagueClient.exe。正如我們以前所說的那樣,編譯器會將C:\Riot代碼變爲C:Riot,所以它試圖運行程序C:Riot,當然它找不到它,所以它會給你提到的錯誤。無論如何,爲了告訴計算機空間實際上是文件名的一部分,必須在文件名周圍加上引號"。如前所述,要在字符串中使用引號,請使用\"。所以正確的做法是system("start \"C:\\Riot Games\\League of Legends\\LeagueClient.exe\"")。另外,start打開控制檯,所以如果你想打開程序本身,只需使用system("\"C:\\Riot Games\\League of Legends\\LeagueClient.exe\"")

與您的代碼的另一個問題是,true沒有用C語言定義所以,你應該要麼使用while(1)或定義true作爲使用#define true 1宏。

所以正確的代碼將是如下:

#include <stdio.h> 
#include <stdlib.h> 
#include <time.h> 
//#define _WIN32_WINNT 0x0500 
#include <windows.h> 

#ifndef true //test if true is defined in case it's already defined somewhere else 
#define true 1 
#endif 

int main() { 
    POINT mouse; 
    //HWND hWnd = GetConsoleWindow(); 
    //ShowWindow(hWnd, SW_MINIMIZE); 
    //ShowWindow(hWnd, SW_HIDE); 
    // how to open program ? 
    system("\"C:\\Riot Games\\League of Legends\\LeagueClient.exe\""); 

    while (true) { 
     GetCursorPos(&mouse); 
     int x = mouse.x; 
     int y = mouse.y; 
     SetCursorPos(x + rand() % 40 - 20, y + rand() % 40 - 20); 
     printf("x = %d ", mouse.x); 
     printf("y = %d\n", mouse.y); 
     Sleep(1); 
    } 
} 
+0

它的工作表示感謝!但是當我嘗試系統(記事本)進行測試時,它打開記事本並停止了程序,直到我關閉了記事本但是與LeagueClient。exe因爲某種原因它沒有停止該程序的任何想法爲什麼?只是好奇。 –

0

使用系統()不是很安全,並創造過程好方法是CreateProcess()函數。其他的東西 - system()等待直到啓動的程序停止,並且在並行之後執行代碼。