VC 拷贝程序到启动目录,实现自启动

// StartDirecotry.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#define _WIN32_WINNT 0x0501
#include 
#include 
using namespace std;
#include 
#include 
#include 
#pragma comment(lib, "User32.lib")
#define BUFSIZE 256
#define PRODUCT_PROFESSIONAL	 0x00000020 //这两个宏定义找不到,可能需要高版本的sdk 7.0
#define VER_SUITE_WH_SERVER 0x00008000 //这两个宏定义找不到,可能需要高版本的sdk 7.0,本人没有测试

int main(int argc, char* argv[])
{
    char szSysPath[MAX_PATH] = { 0 };
    char szStartDirectory[MAX_PATH] = { 0 };
    char szFileName[MAX_PATH] = { 0 };

    GetSystemDirectory(szSysPath, MAX_PATH);
    strncpy(szStartDirectory, szSysPath, 3);
	//先判断操作系统版本
	OSVERSIONINFOEX osvi;
	BOOL bOsVersionInfoEx;
	ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
	osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
	bOsVersionInfoEx = GetVersionEx((OSVERSIONINFO*) &osvi);
	if( ! bOsVersionInfoEx )
		return 1;
	char tmp[1024];
	sprintf(tmp,"%d %d",osvi.dwMajorVersion,osvi.dwMinorVersion);
	MessageBoxA(NULL,tmp,"系统提示",0);
	if (osvi.dwMajorVersion >= 6 )
	{
		//win7 win8
		strcat(szStartDirectory,"ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\test.exe");

	}else{
		strcat(szStartDirectory,
			"Documents and Settings\\All Users\\「开始」菜单\\程序\\启动\\test.exe");//xp可以 win7 不行
	}
    //strcat(szStartDirectory,
        //"Documents and Settings\\All Users\\「开始」菜单\\程序\\启动\\test.exe");//xp可以 win7 不行
	//strcat(szStartDirectory,"Documents and Settings\\yunshouhu\\「开始」菜单\\程序\\启动\\test.exe"); //xp可以 win7 不行
	//strcat(szStartDirectory,"ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\test.exe");//win7 成功 艹,为什么中文不行
	//strcat(szStartDirectory,"Users\\Administrator\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\test.exe");//win7成功 不能使用中文路径?
	OutputDebugString(szStartDirectory);
    GetModuleFileName(NULL, szFileName, MAX_PATH);
    BOOL ret=CopyFile(szFileName, szStartDirectory, FALSE);
	char str[1024];
	ZeroMemory(str,1024);
	if(ret==FALSE)
	{
		TCHAR szBuf[1024];
		LPVOID lpMsgBuf;
		DWORD dw=GetLastError();
		FormatMessage(
			FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
			NULL,dw,
			MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
			(LPTSTR) &lpMsgBuf,0, NULL );
		wsprintf(szBuf,_T("%s \n出错信息 (出错码=%d): %s\n"),szStartDirectory,
			dw, lpMsgBuf);
		LocalFree(lpMsgBuf);
		//输出提示。
		OutputDebugString(szBuf);
		MessageBoxA(NULL,szBuf,"系统提示",0);
	}else{
		
		OutputDebugString("拷贝成功!");
		MessageBoxA(NULL,"拷贝成功","系统提示",0);
	}
	

	return 0;
}

你可能感兴趣的:(VC++)