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

相關問題