1

我正在使用C++在Visual Studio 2015中开发Windows应用程序。我需要GetForegroundWindow()GetWindowText()才能返回当前关注的应用程序。但是,它说GetForegroundWindow()GetWindowText()是未定义的,即使我包含“windows.h”。我试着去GetForegroundWindow()的定义,它导致我到“WinUser.h”,所以我也包含了“WinUser.h”。但它仍然没有帮助。这里是我的代码:Visual Studio 2015中的“GetForegroundWindow:标识符未找到”

#include "MainPage.xaml.h" 
#include <windows.h> 
#include <WinUser.h> 
#include <winapifamily.h> 
#include <string> 
#include <stdio.h> 
#include <iostream> 

using namespace App1; 
using namespace Platform; 
using namespace Windows::Foundation; 
using namespace Windows::Foundation::Collections; 
using namespace Windows::UI::Xaml; 
using namespace Windows::UI::Xaml::Controls; 
using namespace Windows::UI::Xaml::Controls::Primitives; 
using namespace Windows::UI::Xaml::Data; 
using namespace Windows::UI::Xaml::Input; 
using namespace Windows::UI::Xaml::Media; 
using namespace Windows::UI::Xaml::Navigation; 
using std::cout; 
using std::endl; 

MainPage::MainPage() 
{ 
InitializeComponent(); 
} 

HWND currenthwnd, hwnd = NULL; 
char wnd_title[1024]; 

void App1::MainPage::Focus_app_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) 
{ 
currenthwnd = GetForegroundWindow(); 
GetWindowText(hwnd, wnd_title, sizeof(wnd_title)); 
cout << wnd_title << endl; 
} 

任何想法?提前致谢!

+3

您正在编写WinRT应用程序,而不是桌面应用程序。你不能使用许多传统的winapi函数,比如GetForegroundWindow()。你也不允许与这样的其他进程交互,WinRT应用运行在禁止这种交互的沙箱中。这样可以让从商店下载应用的用户感到满意。当然,很高的可能性,你只是使用错误的项目模板开始。 –

+0

@HansPassant我明白了!我正在使用通用Windows应用程序模板。有没有什么办法可以检测到目前使用此模板关注的应用程序?或者我应该创建一个win32/Windows Forms/WPF应用程序?谢谢! – Lolo

+0

我不是在开玩笑。当另一个应用程序获取前景时,您的应用程序甚至不再运行。 –

回答

4

GetForegroundWindow and GetWindowTextWinUser.h#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)宏块内部声明。所以你只能将它们用于Windows桌面应用程序。

+0

谢谢!我只是试图添加声明,错误消失了。但它在App.xaml.obj中抛出了新的错误,声明“LINK2019:未解析的外部符号public:__cedcl ..”,这是我之前没有看到的。你知道发生了什么事吗?对不起,我是新来的Visual Studio和Windows。 – Lolo

+0

当然会的。该API不适用于您的目标平台,因此您无法使用这些方法。没有办法绕过它。 – Ari0nhh

+0

但是我的目标平台就像你说的那样是windows桌面。如果没有办法,你知道我可以使用其他方法吗?谢谢! – Lolo

相关问题