View previous topic :: View next topic |
Author |
Message |
Anatolii
Joined: 05 Dec 2006 Posts: 2
|
(Separately) Posted: Tue Dec 05, 2006 17:33 Post subject: Handle окна |
|
|
Подскажите, кто знает,
Как можно получить Хэндл окна Командера из DLL-ки
Т.Е
BOOL APIENTRY DllMain( HANDLE __hModule,
__hModule - есть, можно ли с него Хэндл окна получить???? |
|
Back to top |
|
|
D1P
Joined: 20 Dec 2004 Posts: 2973 Location: Тбилиси
|
|
Back to top |
|
|
Anatolii
Joined: 05 Dec 2006 Posts: 2
|
(Separately) Posted: Wed Dec 06, 2006 11:12 Post subject: |
|
|
ДА Длл - плагин TC
FindWindow("TTOTAL_CMD",nil); Не подходит, так как Командеров может быть запущенно несколько , а плагин будет вызываться только в одном...
Вот как определить именно ЭТО окно ...
|
|
Back to top |
|
|
Моторокер
Joined: 06 May 2005 Posts: 1517 Location: г. Пермь (читается Перьмь)
|
(Separately) Posted: Wed Dec 06, 2006 11:15 Post subject: |
|
|
D1P wrote: | Длл - плагин TC или что-то другое? И чем FindWindow не подходит?
HWND FindWindow("TTOTAL_CMD",nil); |
Как узнать, что именно этот экземпляр вызвал dll?
Триды просмотривать?
Может как-то проще можно?
Хочу из плагина галочку снять «Отдельные архивы для каждого файла» _________________ плагины для Total Commander, статьи Graphics Converter; NSCopy; SEO HTML; KillOK; Плагин на Delphi
ПармаСруб - строительство домов и бань в Перми |
|
Back to top |
|
|
DeathStalker
Joined: 01 Sep 2006 Posts: 331 Location: Санкт-Петербург
|
(Separately) Posted: Wed Dec 06, 2006 11:51 Post subject: |
|
|
Функция возвращает хэндел процесса который загрузил dll (сам не пользовался)
Справка Win32 Developer's References wrote: | The GetModuleHandle function returns a module handle for the specified module if the file has been mapped into the address space of the calling process.
HMODULE GetModuleHandle(
LPCTSTR lpModuleName // address of module name to return handle for
);
Parameters
lpModuleName
Points to a null-terminated string that names a Win32 module (either a .DLL or .EXE file). If the filename extension is omitted, the default library extension .DLL is appended. The filename string can include a trailing point character (.) to indicate that the module name has no extension. The string does not have to specify a path. The name is compared (case independently) to the names of modules currently mapped into the address space of the calling process.
If this parameter is NULL, GetModuleHandle returns a handle of the file used to create the calling process.
Return Values
If the function succeeds, the return value is a handle to the specified module.
If the function fails, the return value is NULL. To get extended error information, call GetLastError.
Remarks
The returned handle is not global, inheritable, or duplicative, and it cannot be used by another process.
The handles returned by GetModuleHandle and LoadLibrary can be used in the same functions ¾ for example, GetProcAddress, FreeLibrary, or LoadResource. The difference between the two functions involves the reference count. LoadLibrary maps the module into the address space of the calling process, if necessary, and increments the module's reference count, if it is already mapped. GetModuleHandle, however, returns the handle of a mapped module without incrementing its reference count.
Note that the reference count is used in FreeLibrary to determine whether to unmap the function from the address space of the process. For this reason, use care when using a handle returned by GetModuleHandle in a call to FreeLibrary because doing so can cause a dynamic-link library (DLL) module to be unmapped prematurely.
This function must also be used carefully in a multithreaded application. There is no guarantee that the module handle remains valid between the time this function returns the handle and the time it is used by another function. For example, a thread might retrieve a module handle by calling GetModuleHandle. Before the thread uses the handle in another function, a second thread could free the module and the system could load another module, giving it the same handle as the module that was recently freed. The first thread would then be left with a module handle that refers to a module different than the one intended. |
_________________ Гугль - это Матрица, чем меньше его спрашивать, тем слабее будут машины во время Великой Битвы
TC10.00b6 x86 Windows 10 x64 (Windows 7 x64) |
|
Back to top |
|
|
CaptainFlint
Joined: 14 Dec 2004 Posts: 6151 Location: Москва
|
(Separately) Posted: Wed Dec 06, 2006 12:51 Post subject: |
|
|
DeathStalker
Так хэндл процесса и так есть, нужен хэндл окна. _________________ Почему же, ё-моё, ты нигде не пишешь "ё"? |
|
Back to top |
|
|
Maximus
Joined: 07 Apr 2005 Posts: 927 Location: Украина, Кировоградская обл., г. Знаменка
|
(Separately) Posted: Wed Dec 06, 2006 13:19 Post subject: |
|
|
Code: | dwThreadID = GetCurrentThreadId();
EnumThreadWindows(dwCurThreadID,(WNDENUMPROC)EnumThreadWndProc,0); |
Code: | BOOL CALLBACK EnumThreadWndProc(HWND hWindow,LPARAM lParam)
{
char WindowText[256];
GetWindowText(hWindow,WindowText,256);//это просто чтобы посмотреть, какие окна ловятся
char WindowClass[256];
GetClassNameA(hWindow,WindowClass,256);//это тоже
if(IsWindowVisible(hWindow))
{
//это чтобы поймать видимое в данный момент окно. Не помню как работает, если активено модальное окно
//если не прокатит -- придется придумать другой способ
hRetWnd=hWindow;
return false;
}
if(hWindow==NULL) return false;
return true;
} |
_________________ tcPhonebook|AppLoader|Українізація TC|Ultimate Calendar |
|
Back to top |
|
|
Hram
Joined: 19 May 2005 Posts: 113 Location: Питер
|
(Separately) Posted: Tue Aug 21, 2007 23:37 Post subject: |
|
|
Maximus, спасибо!!! |
|
Back to top |
|
|
VadiMGP
Joined: 21 Mar 2007 Posts: 1625
|
(Separately) Posted: Wed Aug 22, 2007 12:59 Post subject: |
|
|
Листер тоже создает окно верхнего уровня в том же потоке. Поэтому я бы посоветовал для большей надежности заменить проверку IsWindowVisible, на сравнение имени класса
Code: | GetClassName(hWindow,WindowClass,256);
if (strcmp(WindowClass,"TTOTAL_CMD")==0)
{
...
}
|
|
|
Back to top |
|
|
VinSmile
Joined: 02 Nov 2007 Posts: 2
|
(Separately) Posted: Fri Nov 02, 2007 13:49 Post subject: |
|
|
Доброго всем времени суток. Тут уже довольно много написано о получении дескриптора окна Total Commander, но все же хочу спросить:
Есть несколько методов для получения этого дескриптора, каким из них предпочтительней пользоваться? Я приведу три из них, которые с моей точки зрения, "имеют смысл быть"
1. Проще всего использовать функцию FindWindow( "TTOTAL_CMD", NULL ) в том месте где нужно получить дескриптор, это еще удобно тем, что не нужно использовать глобальные переменные (хотя в данном случае это не очень страшно, так как дескриптор будет один для всех ). Но!!! Но, поскольку эта функция ищет окна в их Z порядке начиная с верху, нужно быть точно уверенным что в данный момент "нужный" экземпляр Total Commander - а использовался последним среди всех, возможно, открытых!!!
2. Гораздо надежней использовать поиск окна по классу, в процессе в котором этот плагин запущен (Пример выше, в посте от Maximus с поправкой от VadiMGP)... Но метод на много более громоздкой, и подразумевает использование глобальных переменных ( эх... как без них сложно )
3. Использовать параметр MainWin из функции FsExecuteFile()... Тут нужно немного уточнить... Почему то, при первом обращении к плагину (для каждой сессии Total Commander), она вызывается с пустой строкой в качестве параметра RemoteName. Я пытался найти описание этого случая в спецификации, но там ни слова... Если кто-то имеет более подробную спецификацию, отпишите пожалуйста!!! Так как это наиболее простой способ получить дескриптор окна!!! |
|
Back to top |
|
|
VadiMGP
Joined: 21 Mar 2007 Posts: 1625
|
(Separately) Posted: Fri Nov 02, 2007 15:08 Post subject: |
|
|
VinSmile
Первый вызов с пустой строкой сделан для FTP плагинов и устанавливает "MODE I". Зачем это нужно Гислер когда-то говорил, но я не помню.
VinSmile wrote: | Так как это наиболее простой способ получить дескриптор окна! | Да, но этот метод имеет свои недостатки.
1. Он пригоден только если речь идет о работе из FS-плагина. Для остальных типов плагинов нужен другой метод.
2. Он годится только если ты железно уверен, что тебе не потребуется окно ТС до того, как будет вызвана функция FsExecuteFile() в первый раз. Иначе он бесполезен.
А в методе 2, кстати, глобальные переменные вовсе не обязательны. Исключительно дело вкуса. |
|
Back to top |
|
|
VinSmile
Joined: 02 Nov 2007 Posts: 2
|
(Separately) Posted: Fri Nov 02, 2007 16:20 Post subject: |
|
|
VadiMGP
Спасибо за ответ! Я начал писать wfx плагин, потому и столкнулся с этим, не знал что в других типах плагинов оно по другому... Приму во внимание. |
|
Back to top |
|
|
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
Powered by phpBB © 2001, 2005 phpBB Group
|