基于MFC获得主板序列号

const long MAX_COMMAND_SIZE = 10000; // 命令行输出缓冲大小	
	WCHAR szFetCmd[]			= _T("wmic BaseBoard get SerialNumber"); // 获取主板序列号命令行	
	CString strEnSearch;
	strEnSearch.Format(_T("SerialNumber")); // 主板序列号的前导信息
	
	
	char			szReadResult[MAX_COMMAND_SIZE+1] = {0}; // 放置命令行结果的输出缓冲区
	CString			strBuffer;
	unsigned long	count = 0;
	long			ipos  = 0;
	
	BOOL   bret		  = FALSE;
	HANDLE hReadPipe  = NULL; //读取管道
	HANDLE hWritePipe = NULL; //写入管道	
	PROCESS_INFORMATION pi;   //进程信息	
	STARTUPINFO			si;	  //控制命令行窗口信息
	SECURITY_ATTRIBUTES sa;   //安全属性

	memset(&pi, 0, sizeof(pi));
	memset(&si, 0, sizeof(si));
	memset(&sa, 0, sizeof(sa));

	pi.hProcess = NULL;
	pi.hThread  = NULL;
	si.cb		= sizeof(STARTUPINFO);
	sa.nLength	= sizeof(SECURITY_ATTRIBUTES);
	sa.lpSecurityDescriptor = NULL;
	sa.bInheritHandle		= TRUE;

	//1.0 创建管道
	bret = CreatePipe(&hReadPipe, &hWritePipe, &sa, 0);
	if(!bret)
	{
		goto END;
	}

	//2.0 设置命令行窗口的信息为指定的读写管道
	GetStartupInfo(&si);
	si.hStdError	= hWritePipe;
	si.hStdOutput	= hWritePipe;
	si.wShowWindow	= SW_HIDE; //隐藏命令行窗口
	si.dwFlags		= STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;

	//3.0 创建获取命令行的进程
	bret = CreateProcess(NULL, szFetCmd, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi );
	if(!bret)
	{
		goto END;
	}	

	//4.0 读取返回的数据
	WaitForSingleObject (pi.hProcess, 500/*INFINITE*/);
	bret  =  ReadFile(hReadPipe,  szReadResult,  MAX_COMMAND_SIZE,  &count,  0);
	if(!bret)
	{
		goto END;
	}

	//5.0 查找主板序列号
	bret = FALSE;
	strBuffer = szReadResult;
	//strBuffer.Format(_T("%s"),szBuffer);
	ipos = strBuffer.Find(strEnSearch);

	if (ipos < 0) // 没有找到主板序列号的前导信息,即没有找到主板序列号
	{		
		goto END;
	}
	else
	{
		//读出的结果包含主板序列号前导信息 空格  主板序列号三部分;
		//首先去除前导信息。
		strBuffer = strBuffer.Right(strBuffer.GetLength() - strEnSearch.GetLength());
		//然后去除空格
		CString result1;
		result1 = strBuffer.Trim();
		TRACE(result1);//将结果trace到输出窗口
	}	
	bret = TRUE;
END:
	//关闭所有的句柄
	CloseHandle(hWritePipe);
	CloseHandle(hReadPipe);
	CloseHandle(pi.hProcess);
	CloseHandle(pi.hThread);

你可能感兴趣的:(基于MFC获得主板序列号)