x625802392 发表于 2018-6-23 12:34:05

VS2012+C语言+设置程序开机自动启动+示例

#include <stdio.h>  
#include <windows.h>
  
#include <stdlib.h>
  
char* ReplaceString(const char *srcStr, const char *src, const char *dest)//替换字符串,获得文件路径
  
{
  char *ptr;
  int len = strlen(srcStr);
  ptr = (char*)malloc(sizeof(char)*len+1);
  strcpy(ptr, srcStr);
  for ( int i=0; i<len; ++i )
  {
  if ( 0==strncmp(&ptr, src, strlen(src)) )    //查找想要被替换字符串的起始位置
  {
  strncpy(&ptr, dest, strlen(dest));   //替换字符串的长度为目标字符串的长度
  }
  }
  ptr = '\0';   //计算出字符串结束位置,并加上‘/0’
  return ptr;
  
}
  
int StartupRun(const char *key, const char *path)   //key启动项名称,path为要开机启动的程序
  
{
  HKEY hKey;
  DWORD dwDisposition;
  LONG result = RegCreateKeyEx(   //用来创建注册表键,如果该键已经存在,则打开它(注册表键不区分大小写)
  HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run",
  NULL, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS,
  NULL, &hKey, &dwDisposition );
  if(result != ERROR_SUCCESS)
  {
  RegCloseKey(hKey);
  return 0;
  }
  result = RegSetValueEx(hKey, key, NULL, REG_SZ, (const unsigned char *)path, strlen(path)+1);   //在注册表项下设置指定值的数据和类型。
  if(result != ERROR_SUCCESS)
  {
  RegCloseKey(hKey);
  return 0;
  }
  RegCloseKey(hKey);
  return 1;
  
}
  
int main(int argc,char *argv[])
  
{
  //StartupRun("偷闲--开机启动程序", "C:\\Users\\Administrator\\Documents\\Visual Studio 2012\\Projects\\tx\\Release\\tx.exe");   //绝对路径
  //StartupRun("偷闲--开机启动程序", ".\\tx.exe");//不可用
  printf("获取程序当前路径:");
  printf(argv);    //argv为当前程序的路径
  printf("\n");
  const char *str;
  str = ReplaceString(argv, "StartRun.exe", "tx.exe"); //StartRun.exe为当前程序的名称,tx.exe为想要开机启动程序的名称,二者在同一目录下
  StartupRun("偷闲--开机启动程序1.0", str);
  printf("\n设置开机启动程序路径:");
  printf(str);
  printf("\n\n设置成功\n\n");
  system("pause");
  return 0;
  
}
页: [1]
查看完整版本: VS2012+C语言+设置程序开机自动启动+示例