网址自动补全/跳转
2026-08-17 16:58:43
发布于:四川
经过bor长达一周的研究,bor悟了,今天我们就来讲解一下c++中ShellExecuteA的用法
1.1、基本的定义(这玩意bor不敢瞎说,万一c++之父半夜爬起来找我怎么办,网上搜的):
ShellExecuteA 是 Windows API 中的一个函数,用于对指定文件或对象执行操作,例如打开文件、打印文档或启动程序。
示例:打开文件
以下代码展示了如何使用 ShellExecuteA 打开一个文本文件:
#include <windows.h>
int main() {
ShellExecuteA(
NULL, // 父窗口句柄
"open", // 操作类型(如 "open"、"print")
"example.txt", // 文件路径
NULL, // 参数(仅用于可执行文件)
NULL, // 默认工作目录
SW_SHOWNORMAL // 显示窗口的方式
);
return 0;
}
1.2参数说明
-
hwnd: 父窗口句柄,用于显示错误消息或 UI。
-
lpOperation: 指定操作类型,如 "open"(打开)、"print"(打印)。
-
lpFile: 要操作的文件或对象路径。
-
lpParameters: 如果是可执行文件,可传递参数;否则为 NULL。
-
lpDirectory: 默认工作目录。
-
nShowCmd: 窗口显示方式,例如 SW_SHOWNORMAL。
1.3返回值
-
成功时返回值大于 32。
-
失败时返回错误代码,例如: ERROR_FILE_NOT_FOUND: 找不到指定文件。 ERROR_PATH_NOT_FOUND: 找不到路径。 SE_ERR_ACCESSDENIED: 拒绝访问。
1.4注意事项
1.在调用前建议初始化 COM 环境,使用 CoInitializeEx。
2.如果需要更多控制(如获取启动的进程信息),可以使用更高级的 ShellExecuteEx 函数。
1.5适用于
此函数适用于 Windows XP 及更高版本,头文件为 shellapi.h,链接库为 Shell32.lib。
二、实现网址的自动补全
2.1初始思想
为了达成浏览器中输入:baidu.com,自动补全并跳转为:https://www.baidu.com
我们的初始策略为直接加上https://www.的前缀,但这个结论在完成源代码的测试阶段重新出现了问题:
- [存在问题|ERROR]若用户并没有只输入后缀,直接输入,如:https://www.baidu.com,在经过处理后就会变成:https://https://www.baidu.com,但这个网址是不存在并且有误的,所以推翻结论
- [存在问题|ERROR]若用户想访问的网址的前缀不是www.,强制添加前缀www.就会出错,所以推翻结论
2.2初始代码
#include<bits/stdc++.h>
#include<windows.h>
#include<shellapi.h>
using namespace std;
void ask(char com[256])
{
ShellExecuteA(0, "open", com, NULL, NULL, SW_SHOW);
}
int main(){
while(1){
string com;
cout << "请输入网址(URL,0:退出):";
cin >> com;
if(com=="0"){
return 0;
}
string fullUrl = "https://www."+com;
cout << "最终使用地址:" << fullUrl << endl;
char a[256] = {0};
strncpy(a, fullUrl.c_str(), sizeof(a)-1);
ask(a);
}
return 0;
}
三、改变思路
由于前面推翻了结论,所以我们添加上判定,并添加提示弹窗再制作一遍
结果虽然并没有多好,但勉强能用...
四、最终敲定代码
#include<bits/stdc++.h>
#include<windows.h>
#include<shellapi.h>
using namespace std;
// 模拟判断:一些域名裸域名无法访问,需要www
bool needAddWww(const string& domain)
{
// 这里可以自行扩充列表
unordered_set<string> needWwwList = {
"doubao.com"
};
return needWwwList.count(domain);
}
string autoCompleteUrl(string input)
{
// 已经带http/https,直接原样返回
if(input.substr(0,7)=="http://" || input.substr(0,8)=="https://")
{
return input;
}
// 已经自带www.
if(input.substr(0,4)=="www.")
{
return "https://" + input;
}
// 裸域名
if(needAddWww(input))
{
return "https://www." + input;
}
else
{
return "https://" + input;
}
}
void ask(char com[256])
{
string msg = "正在跳转至";
msg += com;
msg += ",是否打开该网页?";
int ret1 = MessageBoxA(0, msg.c_str(), "确认", MB_YESNO | MB_ICONASTERISK);
if (ret1 == IDYES)
{
ShellExecuteA(0, "open", com, NULL, NULL, SW_SHOW);
}
}
int main(){
while(1){
string com;
cout << "请输入网址(URL,0:退出):";
cin >> com;
if(com=="0"){
return 0;
}
string fullUrl = autoCompleteUrl(com);
cout << "最终使用地址:" << fullUrl << endl;
char a[256] = {0};
strncpy(a, fullUrl.c_str(), sizeof(a)-1);
ask(a);
}
return 0;
}//判定可能会失效,敬请谅解
感谢阅读,点个赞吧!
感谢一下
此文章的所有代码和棋类大全的网页跳转代码灵感都来源于:acgo OJ用户:@三个王国的战争
这里空空如也




















有帮助,赞一个