C++ 使用LockWorkStation的过程遇到的问题[通俗易懂]

发布时间:2025-12-09 13:56:18 浏览次数:4

关于函数“LockWorkStation()”,参见:https://msdn.microsoft.com/en-us/library/windows/desktop/aa376875.aspx

How to Lock the Workstation (如何锁定工作站),参见:https://msdn.microsoft.com/zh-cn/library/windows/desktop/aa376869

看了MSDN提供的“How to Lock the Workstation”例子,觉得挺蛮简洁的。于是自己也试试,Ctrl + C、Ctrl + V,稍微修改一下。

IDE: Code::Blocks

操作系统:Windows 7 x64

 1 #include <windows.h> 2 #include <stdio.h> 3  4 #pragma comment( lib, "user32.lib" ) 5  6 int main() 7 { 8     // Lock the workstation. 9 10     if( !LockWorkStation() )11         printf ("LockWorkStation failed with %lu \n", GetLastError());12 13     return 0;14 }

Build… What the hell? 居然有错!

error: ‘LockWorkStation’ was not declared in this scope

于是各种折腾… 不说,心累啊!

上网找,最终找到了解决方法,网友给出的解决方法,http://blog.csdn.net/kelsel/article/details/52758448,还有他找到的参考:http://oldbbs.rupeng.com/thread-4007-1-1.html


在Code::Blocks中,可以通过右击函数“LockWorkStation()”,Find declaration of: ‘LockWorkStation’定位到该函数所在的头文件“winuser.h”。

如果你细心一些,就可以发现,这个函数被限制在条件编译语句里:(我不够细心啊!!!)

#if (_WIN32_WINNT >= 0x0500)WINUSERAPI BOOL WINAPI LockWorkStation(void);#endif

只有当_WIN32_WINNT >=0x0500,LockWorkStation()才能被编译。

再看看关于_WIN32_WINNT的定义:

#ifndef WINVER#define WINVER 0x0400/* * If you need Win32 API features newer the Win95 and WinNT then you must * define WINVER before including windows.h or any other method of including * the windef.h header. */#endif#ifndef _WIN32_WINNT#define _WIN32_WINNT WINVER/* * There may be the need to define _WIN32_WINNT to a value different from * the value of WINVER.  I don't have any example of why you would do that. * However, if you must then define _WIN32_WINNT to the value required before * including windows.h or any other method of including the windef.h header. */#endif

从上面的宏定义,我们可以知道,_WIN32_WINNT的值等于0x0400。

这下清楚了,实际上_WIN32_WINNT小于0x0500,那LockWorkStation()怎么可能会被编译呢?所以只能报错了!

解决方法是在包含头文件之前使用“#define WINVER 0x0500”或“#define _WIN32_WINNT0x0500”。

来,把代码改改:

 1 //#define WINVER 0x0500 2 #define _WIN32_WINNT 0x0500 3  4 #include <windows.h> 5 #include <stdio.h> 6  7 using namespace std; 8  9 int main()10 {11     // Lock the workstation.12 13     if( !LockWorkStation() )14         printf ("LockWorkStation failed with %lu \n", GetLastError());15 16     return 0;17 }

难受,睡个觉。。。

需要做网站?需要网络推广?欢迎咨询客户经理 13272073477