您的位置:首页 > 编程语言 > Qt开发

Qt获取CPU序列号,亲测可用

2018-02-01 10:08 169 查看


前言

对于windows系统下获取CPU序列号,网上有很多方式,通过C++调用windows的接口可以实现,不过代码都很复杂,不易理解,并且还还不一定能成功。这里用一种非常简单的方式去获取CPU序列号,通过Qt的接口,代码超级简单,不超过十行。(原创:http://blog.csdn.net/luoyayun361/article/details/70837497)


正文

查看CPU序列号的方式很多,可以通过命令行查询,或者借助第三方软件查看,那么,这里要用到的方式就是在程序中通过执行命令行来获取。需要用刀Qt的类QProcess 

代码如下:
QString cpu_id = "";
QProcess p(0);
p.start("wmic CPU get ProcessorID");    p.waitForStarted();
p.waitForFinished();
cpu_id = QString::fromLocal8Bit(p.readAllStandardOutput());
cpu_id = cpu_id.remove("ProcessorId").trimmed();
1
2
3
4
5
6
7
代码最后一行经过对输出的终端信息进行处理 最终得到单独的CPU序列号信息。
以上方式可能在某些机子上无法正常获取,接下来通过一种复杂的方式来获取 CPU 序列号。 

直接上代码
static void getcpuid(unsigned int CPUInfo[4], unsigned int InfoType);
static void getcpuidex(unsigned int CPUInfo[4], unsigned int InfoType, unsigned int ECXValue);
static QString get_cpuId();

QString get_cpuId()
{
QString cpu_id = "";
unsigned int dwBuf[4]={0};
unsigned long long ret = 0;
getcpuid(dwBuf, 1);
ret = dwBuf[3];
ret = ret << 32;

QString str0 = QString::number(dwBuf[3], 16).toUpper();
QString str0_1 = str0.rightJustified(8,'0');//这一句的意思是前面补0,但是我遇到的情况是这里都填满了
QString str1 = QString::number(dwBuf[0], 16).toUpper();
QString str1_1 = str1.rightJustified(8,'0');//这里必须在前面补0,否则不会填满数据
//cpu_id = cpu_id + QString::number(dwBuf[0], 16).toUpper();
cpu_id = str0_1 + str1_1;
return cpu_id;
}

void getcpuid(unsigned int CPUInfo[4], unsigned int InfoType)
{
#if defined(__GNUC__)// GCC
__cpuid(InfoType, CPUInfo[0], CPUInfo[1], CPUInfo[2], CPUInfo[3]);
#elif defined(_MSC_VER)// MSVC
#if _MSC_VER >= 1400 //VC2005才支持__cpuid
__cpuid((int*)(void*)CPUInfo, (int)(InfoType));
#else //其他使用getcpuidex
getcpuidex(CPUInfo, InfoType, 0);
#endif
#endif
}
void getcpuidex(unsigned int CPUInfo[4], unsigned int InfoType, unsigned int ECXValue)
{
#if defined(_MSC_VER) // MSVC
#if defined(_WIN64) // 64位下不支持内联汇编. 1600: VS2010, 据说VC2008 SP1之后才支持__cpuidex.
__cpuidex((int*)(void*)CPUInfo, (int)InfoType, (int)ECXValue);
#else
if (NULL==CPUInfo)  return;
_asm{
// load. 读取参数到寄存器.
mov edi, CPUInfo;
mov eax, InfoType;
mov ecx, ECXValue;
// CPUID
cpuid;
// save. 将寄存器保存到CPUInfo
mov [edi], eax;
mov [edi+4], ebx;
mov [edi+8], ecx;
mov [edi+12], edx;
}
#endif
#endif
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: