问题描述
对于 Metro 应用程序,有 Windows.Devices.Input.KeyboardCapabilities.KeyboardPresent.有没有办法让 Windows 8 桌面程序检测物理键盘是否存在?
For Metro apps there's Windows.Devices.Input.KeyboardCapabilities.KeyboardPresent.Is there a way for Windows 8 desktop programs to detect whether a physical keyboard is present?
推荐答案
在 Windows 10 上,此 API 是 UWP API 的一部分,可以从桌面应用程序调用就好了.
On Windows 10 this API is part of the UWP API and can be called from Desktop applications just fine.
要从 C#(或其他 .NET 语言)调用它,您需要添加一些对项目文件的引用:
To call it from C# (or other .NET languages) you need to add a few references to the project files:
<Reference Include="System.Runtime.WindowsRuntime" />
<Reference Include="Windows.Foundation.FoundationContract">
<HintPath>C:Program Files (x86)Windows Kits10References10.0.16299.0Windows.Foundation.FoundationContract3.0.0.0Windows.Foundation.FoundationContract.winmd</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="Windows.Foundation.UniversalApiContract">
<HintPath>C:Program Files (x86)Windows Kits10References10.0.16299.0Windows.Foundation.UniversalApiContract5.0.0.0Windows.Foundation.UniversalApiContract.winmd</HintPath>
<Private>False</Private>
</Reference>
第一个引用将针对 GAC 进行解析,另外两个在您的 VS 安装中(您可以根据需要选择不同的版本).将 Private 设置为 False 意味着不部署这些程序集的本地副本.
The first reference will be resolved against the GAC, the other two are in your VS installation (you can chose a different version if you want). Setting Private to False means to not deploy a Local Copy of those assemblies.
Console.WriteLine(new Windows.Devices.Input.KeyboardCapabilities().KeyboardPresent != 0 ? "keyboard available" : "no keyboard");
在 C++ 中你可以这样做:
In C++ you can do it as follows:
#include <roapi.h>
#include <wrl.h>
#include <windows.devices.input.h>
#pragma comment(lib, "runtimeobject")
int APIENTRY wWinMain(
_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nCmdShow)
{
RoInitialize(RO_INIT_MULTITHREADED);
{
INT32 isKeyboardAvailable;
Microsoft::WRL::ComPtr<ABI::Windows::Devices::Input::IKeyboardCapabilities> pKeyboardCapabilities;
Microsoft::WRL::Wrappers::HStringReference KeyboardClass(RuntimeClass_Windows_Devices_Input_KeyboardCapabilities);
if (SUCCEEDED(RoActivateInstance(KeyboardClass.Get(), &pKeyboardCapabilities)) &&
SUCCEEDED(pKeyboardCapabilities->get_KeyboardPresent(&isKeyboardAvailable)))
{
OutputDebugStringW(isKeyboardAvailable ? L"keyboard available
" : L"no keyboard
");
}
}
RoUninitialize();
}
这篇关于在 Windows 8 桌面程序中检测键盘是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!