gpt4 book ai didi

c - 如何在c中执行外部程序

转载 作者:行者123 更新时间:2023-11-30 16:50:33 24 4
gpt4 key购买 nike

我想在运行代码后启动计算机中的 .exe 程序,并在程序打开后仍然执行一些操作,但我不知道如何打开它。

#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。

最佳答案

有几个问题是字符串“start C:\Riot Games\League of Legends\LeagueClient.exe”

首先,\ 字符用于转义字符,这意味着输入的字符如果直接插入到字符串中,则具有其他含义。例如,要在字符串中写入 ",您应该使用 \",因为 " 本身就意味着它是字符串的结尾.同样,\n表示换行符,因为你不能直接在字符串中写入换行符。这里,\R位于C:\Riot Games 意味着您正在转义字符 R,这没有任何意义。编译器将 \R 解释为简单的 R ( \L 也是如此),因此将字符串 "start C:\Riot Games\League of Legends\LeagueClient.exe" 转换为 "start C: LegendsLeagueClient.exe 的 Riot GamesLeague"。要转义 \ 字符,请使用 \\。到目前为止,字符串应为 system("启动 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\"")

代码的另一个问题是 C 中未定义 true。因此您应该使用 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);
}
}

关于c - 如何在c中执行外部程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42178944/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com