2017-02-11 34 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()等待直到启动的程序停止,并且在并行之后执行代码。