文档目录
1、实现功能
MFC 实现执行bat内容,而非执行bat文件
2、涉及方法
- MFC创建文件并写入文件数据
- CStringArray使用方法
- MFC Unicode字符集下 CFile CString UTF-8文件 ANSI 文件
3、分解讲解
3.1 MFC创建文件并写入文件数据
CFile file;
file.Open(path,CFile::modeCreate|CFile::modeWrite);
file.Write(str.GetBuffer(),str.GetLength() * sizeof(TCHAR)); //str为CString类型
file.Flush();
file.Close();
3.2 CStringArray使用方法
//CStringArray使用之前先设置数组尺寸SetSize,才能使用SetAt
CStringArray batContents;
batContents.SetSize (5);
batContents.SetAt (0,L"@Echo off");
batContents.SetAt (1,L"cd /d %~dp0");
//直接增加内容Add
CStringArray RegContents;
RegContents.Add(L"@Echo off");
RegContents.Add(L"cd /d %~dp0");
遍历CStringArray
,下面例子是Unicode
模式下的代码,ANSI的需要变形
CStringArray batContents;
batContents.Add(L"A");
batContents.Add(L"B");
batContents.Add(L"C");
batContents.Add(L"D");
CFile file;
CString strTemp;
file.Open(L"C:\a.bat", CFile::modeCreate | CFile::modeWrite);
for (int i = 0; i < batContents.GetSize(); i++)
{
file.Write(batContents[i], batContents[i].GetLength() * sizeof(TCHAR));//str为CString类型
file.Write("\n", 2);
}
file.Flush();
file.Close();
3.3 MFC Unicode字符集下 CFile CString UTF-8文件 ANSI 文件
写ANSI文件时,将Unicode编码的CString转化为ANSI编码的CStringA,要获取ANSI格式的字符只需使用GetBuffer即可。也可使用WideCharToMultiByte转换
CStringArray RegContents;
RegContents.Add(L"@Echo off");
RegContents.Add(L"cd /d %~dp0");
CFile file(_T("test_ANSI.txt"), CFile::modeCreate | CFile::modeWrite);//写ANSI编码的文件
for (int i = 0; i < RegContents.GetSize(); i++)
{
CStringA str_ANSI(RegContents[i].GetBuffer(0));
file.Write(str_ANSI.GetBuffer(), str_ANSI.GetLength());
file.Write("\n", 1);
}
file_ANSI.close();
更多细节: MFC Unicode字符集下 CFile CString UTF-8文件 ANSI 文件
4、总体代码
MFC创建一个bat文件,bat文件的内容是由MFC填充的,执行完毕后删除bat,间接完成该功能
void ExampleDlg::RunBatContentsInMFC()
{
enum CodeType
{
CodeType_Unicode,
CodeType_ANSI
};
//通过设置该变量实现:输出的格式到底是Unicode还是ANSI,根据个人需求
int CodeTypeInUse = CodeType_ANSI;
//获取BatFilePath
wchar_t str[MAX_PATH];
GetModuleFileName(NULL, str, 128);
CString exePath = str;
CString programFolder = exePath.Mid(0, exePath.ReverseFind('\\')) + "\\";
CString RegBatFilePath = programFolder + "com\\m-todo.bat";
//创建File,写入内容
CFile file;
file.Open(RegBatFilePath, CFile::modeCreate | CFile::modeWrite);
CStringArray RegContents;
RegContents.Add(L"@Echo off");
RegContents.Add(L"Echo.");
RegContents.Add(L"Echo Reg Com Lib Success");
RegContents.Add(L"del %0 ");//执行完删除bat本身
for (int i = 0; i < RegContents.GetSize(); i++)
{
//文件写出来采用的是Unicode格式,bat无法执行
if (CodeTypeInUse == CodeType_Unicode)
{
file.Write(RegContents[i], RegContents[i].GetLength() * sizeof(TCHAR));//str为CString类型
file.Write("\n", 2);
}
//文件写出来采用的是ANSI格式,bat可以执行(下述方法是将Unicode转换成ANSI的方法)
else if(CodeTypeInUse == CodeType_ANSI)
{
CStringA str_ANSI(RegContents[i].GetBuffer(0));
file.Write(str_ANSI.GetBuffer(), str_ANSI.GetLength());//str为CString类型
file.Write("\n", 1);
}
}
file.Flush();
file.Close();
//执行bat,bat最后部分是删除自身,所以算是间接不留痕迹
ShellExecute(NULL, _T("open"), RegBatFilePath, _T(""), NULL, SW_SHOW);
}
效果展示
5、推荐文章
下属文章想法很独特,但其内容并我目前并未实现功能,留做后续研究