Главная страница
    Top.Mail.Ru    Яндекс.Метрика
Форум: "Начинающим";
Текущий архив: 2011.04.03;
Скачать: [xml.tar.bz2];

Вниз

Получение имени программы по хендлу окна   Найти похожие ветки 

 
mahab-22   (2010-12-13 23:59) [0]

Всем привет.D7. В ХР пользовался такой ф-ей.
function GetModuleFileNameExW(hProcess:THandle; hModule:HMODULE; lpFilename:PWideChar; nSize:DWORD):DWORD; stdcall; external "PSAPI.DLL";

function WindowGetEXE(wnd:HWND):string;
var
r:integer;
prc:THandle;
prcID:cardinal;
begin
result:="";
if GetWindowThreadProcessID(wnd,prcID)<>0 then
begin
Writeln(t,"prcID -"+inttostr(prcID));
prc:=OpenProcess(PROCESS_ALL_ACCESS,false,prcID);
Writeln(t,"prc -"+inttostr(prc));
if prc<>0 then
try
 r:=GetModuleFileNameExW(prc,GetWindowLong(wnd,GWL_HINSTANCE),wt,MAX_PATH*2);
 if r=0 then r:=GetModuleFileNameExW(prc,0,wt,MAX_PATH*2);
 if r<>0 then   result:=wt;
 Writeln(t,"r -"+inttostr(r));
finally
 CloseHandle(prc)
end ;
end ;
end;
Передаю хендл из Getforeground и все ок.Кстати все это работало в сервисе. Перешел на win7. Проверяю эту ф-ю в приложении win32 все работает, а вот в сервисе не работает. проверил ,что сервис имеет права супер админа т. е. с этим проблем нет. Результаты ф-й GetWindowThreadProcessID,OpenProcess,GetModuleFileNameExW ненулевые. Почему то результат выдает C:\Windows\system32\spool\drivers\w32x86\3\CAPPSWK.EXE а нето приложение которое было "верхним"


 
Игорь Шевченко ©   (2010-12-14 00:06) [1]


> а вот в сервисе не работает


у сервисов свои окна, а в Windows 7 им запрещено взаимодействовать с пользователем, насколько я знаю.


 
mahab ©   (2010-12-14 00:42) [2]

Жаль что если сделать еще один модуль чтобы он как раз взаимодействовал с "пользователем", то без UAC он не запуститься а ему нужны высшие права


 
Anatoly Podgoretsky ©   (2010-12-14 09:31) [3]

> mahab  (14.12.2010 00:42:02)  [2]

Не делай модуль, которому нужны административные права.


 
mahab ©   (2010-12-14 16:38) [4]

Этот модуль должен вести лог в какойнибудь системной папке


 
Rouse_ ©   (2010-12-14 19:10) [5]

Ну попробуй в эту сторону глянуть: http://rouse.drkb.ru/winapi.php#servicenotifyer


 
mahab ©   (2011-01-06 16:41) [6]

Продолжу тему потому как уже много подобных вопросов встретил.

> Rouse_ ©   (14.12.10 19:10) [5]
> Ну попробуй в эту сторону глянуть: http://rouse.drkb.ru/winapi.
> php#servicenotifyer

Посмотрел спасибо, но без обычного приложения все же в этом примере не обйтись а хотелось бы.
Почитал SDK(насколько смог), раздел Interactive Services. Опять таки трактовать можно по разному. Приведу содержание раздела:
Typically, services are console applications that are designed to run unattended without a graphical user interface (GUI). However, some services may require occasional interaction with a user. This page discusses the best ways to interact with the user from a service.

Important  Services cannot directly interact with a user as of Windows Vista. Therefore, the techniques mentioned in the section titled Using an Interactive Service should not be used in new code.

Interacting with a User from a Service Indirectly
(Это говорит о том что можно)

You can use the following techniques to interact with the user from a service on all supported versions of Windows:

Display a dialog box in the user"s session using the WTSSendMessage function.
Create a separate hidden GUI application and use the CreateProcessAsUser function to run the application within the context of the interactive user. Design the GUI application to communicate with the service through some method of interprocess communication (IPC), for example, named pipes. The service communicates with the GUI application to tell it when to display the GUI. The application communicates the results of the user interaction back to the service so that the service can take the appropriate action. Note that IPC can expose your service interfaces over the network unless you use an appropriate access control list (ACL).
If this service runs on a multiuser system, add the application to the following key so that it is run in each session: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run. If the application uses named pipes for IPC, the server can distinguish between multiple user processes by giving each pipe a unique name based on the session ID.

The following technique is also available for Windows Server 2003, Windows XP, and Windows 2000:

Display a message box by calling the MessageBox function with MB_SERVICE_NOTIFICATION. This is recommended for displaying simple status messages. Do not call MessageBox during service initialization or from the HandlerEx routine, unless you call it from a separate thread, so that you return to the SCM in a timely manner.
Using an Interactive Service
By default, services use a noninteractive window station and cannot interact with the user. However, an interactive service can display a user interface and receive user input.
(ЭТО НЕ СУЩЕСТВЕННО)
Caution  Services running in an elevated security context, such as the LocalSystem account, should not create a window on the interactive desktop because any other application that is running on the interactive desktop can interact with this window. This exposes the service to any application that a logged-on user executes. Also, services that are running as LocalSystem should not access the interactive desktop by calling the OpenWindowStation or GetThreadDesktop function.

To create an interactive service, do the following when calling the CreateService function:

Specify NULL for the lpServiceStartName parameter to run the service in the context of the LocalSystem account.
Specify the SERVICE_INTERACTIVE_PROCESS flag.
To determine whether a service is running as an interactive service, call the GetProcessWindowStation function to retrieve a handle to the window station, and the GetUserObjectInformation function to test whether the window station has the WSF_VISIBLE attribute.

However, note that the following registry key contains a value, NoInteractiveServices, that controls the effect of SERVICE_INTERACTIVE_PROCESS:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Windows

The NoInteractiveServices value defaults to 0, which means that services with SERVICE_INTERACTIVE_PROCESS are allowed to run interactively. When NoInteractiveServices is set to a nonzero value, no service started thereafter is allowed to run interactively, regardless of whether it has SERVICE_INTERACTIVE_PROCESS.

Important  All services run in Terminal Services session 0. Therefore, if an interactive service displays a user interface, it is visible only to the user who connected to session 0. Because there is no way to guarantee that the interactive user is connected to session 0, do not configure a service to run as an interactive service under Terminal Services or on a system that supports fast user switching (fast user switching is implemented using Terminal Services).

Вот превод GOOGLE отмеченной части
Внимание служб, работающих в контексте повышенной безопасности, таких как системной учетной записью, не должны создавать окна на интерактивном рабочем столе, поскольку любое другое приложение, которое работает на интерактивном рабочем столе может взаимодействовать с этим окном. Это предоставляет услуги любого приложения, вошедший в систему пользователь выполняет. Кроме того, услуги, которые работают как LocalSystem не должны получать доступ интерактивного рабочего стола по телефону OpenWindowStation или GetThreadDesktop функции.

Чтобы создать интерактивный сервис, выполните следующие действия при вызове CreateService функции:
Укажите NULL для lpServiceStartName параметр для запуска службы в контексте системной учетной записью .
Укажите флаг SERVICE_INTERACTIVE_PROCESS.

Чтобы определить, работает ли служба, как интерактивный сервис, звоните GetProcessWindowStation функцию, чтобы получить дескриптор окна станции, и GetUserObjectInformation функции для проверки окна станции WSF_VISIBLE атрибута.

Однако, отметим, что в следующем разделе реестра содержится значение, NoInteractiveServices, который контролирует влияние SERVICE_INTERACTIVE_PROCESS:

HKEY_LOCAL_MACHINE \ SYSTEM \ CurrentControlSet \ Control \ Windows

Значение NoInteractiveServices по умолчанию 0, что означает, что услуги с SERVICE_INTERACTIVE_PROCESS разрешено запускать в интерактивном режиме. Когда NoInteractiveServices установлен в ненулевое значение, не служба началась после разрешено запускать интерактивном режиме, независимо от того, имеет SERVICE_INTERACTIVE_PROCESS.

Важно Все службы работают в службах терминалов сессии 0. Поэтому, если интерактивный сервис отображает пользовательский интерфейс, она видна только пользователю, который подключен к сессии 0. Потому что не существует способа гарантировать, что интерактивный пользователь подключен к сеансу 0, не настраивайте службы на запуск в качестве интерактивного сервиса под Terminal Services или на системе, которая поддерживает быстрое переключение пользователей (быстрое переключение пользователей осуществляется с помощью служб терминалов) .
(А вот здесь говорится что взаимодействие возможно только под сессию 0)
Конечно все это IMHO как я трактовал.
А еще нет четкого алгоритма построения кода.
Может кто-нибудь встречался с такой задачей.



Страницы: 1 вся ветка

Форум: "Начинающим";
Текущий архив: 2011.04.03;
Скачать: [xml.tar.bz2];

Наверх





Память: 0.51 MB
Время: 0.004 c
2-1294484497
Aleks
2011-01-08 14:01
2011.04.03
Народ подскажите я, что то не то делаю или что то глючит?


15-1292536050
George
2010-12-17 00:47
2011.04.03
Delphi, PHP и md5


15-1292697083
aka
2010-12-18 21:31
2011.04.03
магический квадрат


15-1292621393
Юрий
2010-12-18 00:29
2011.04.03
С днем рождения ! 18 декабря 2010 суббота


15-1292844027
George
2010-12-20 14:20
2011.04.03
Почитать бы





Afrikaans Albanian Arabic Armenian Azerbaijani Basque Belarusian Bulgarian Catalan Chinese (Simplified) Chinese (Traditional) Croatian Czech Danish Dutch English Estonian Filipino Finnish French
Galician Georgian German Greek Haitian Creole Hebrew Hindi Hungarian Icelandic Indonesian Irish Italian Japanese Korean Latvian Lithuanian Macedonian Malay Maltese Norwegian
Persian Polish Portuguese Romanian Russian Serbian Slovak Slovenian Spanish Swahili Swedish Thai Turkish Ukrainian Urdu Vietnamese Welsh Yiddish Bengali Bosnian
Cebuano Esperanto Gujarati Hausa Hmong Igbo Javanese Kannada Khmer Lao Latin Maori Marathi Mongolian Nepali Punjabi Somali Tamil Telugu Yoruba
Zulu
Английский Французский Немецкий Итальянский Португальский Русский Испанский