Add a Console Application
添加引用
#include <iostream>
using namespace std;
AllocConsole();
freopen("CONIN$", "r", stdin );
freopen("CONOUT$", "w", stdout);
freopen("CONERR$", "w", stderr);
cout << "启动控制台/n/n";
在析构函数中调用
FreeConsole();
int main(int argc, char * argv[])
{
char buf[MAX_PATH];
GetConsoleTitle(buf, MAX_PATH);
HWND hwnd = ::FindWindow(NULL, buf);
HMENU hmenu = ::GetSystemMenu(hwnd, FALSE);
if (hwnd)
{
/** @brief 2.禁用控制台窗口的关闭按钮*/
::RemoveMenu(hmenu, SC_CLOSE, MF_BYCOMMAND);
/** @brief 3.控制台程序启动时窗口最小化*/
::SendMessage(hwnd, WM_SYSCOMMAND, SC_MINIMIZE, 0);
}
/** @brief 4.获得服务器启动程序当前路径,并添加到注册表自启动*/
TCHAR workingPath[MAX_PATH];
ZeroMemory(workingPath, MAX_PATH);
if (GetModuleFileName(NULL, workingPath, MAX_PATH) > 0)
{
//设置exe程序的工作路径,这里设置为exe文件所在的位置为工作路径
char path[3000];
memset(path, 0, 3000);
for (int i = strlen(workingPath) - 1; i >= 0; --i)
{
if (workingPath[i] == '\\')
{
strncpy(path, workingPath, i + 1);
break;
}
}
SetCurrentDirectory(path);
//取得当前工作路径成功
HKEY hKey;
if (RegCreateKey(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", &hKey) != ERROR_SUCCESS)
{
//创建注册表成功
}
else
{
if (RegSetValueEx(hKey, "CASCO Log Sever", 0, REG_SZ, (CONST BYTE *)(LPCTSTR)workingPath, strlen(workingPath)) != ERROR_SUCCESS)
{
//设置注册表失败,不自启动
}
else
{
//设置注册表成功,启动设置成功
}
RegCloseKey(hKey);
}
}
else
{
//取得当前工作路径成功失败,不自启动
}
return 0;
}