0

I'm trying to dive into kinda lower level programming with Rust after some experience with Node.js. Currently it is small application that counts time spent within specific windows opened.

I've found that I can use windows crate to interact with Windows API, and there is a function GetForegroundWindow() which works flawlessly. I can just call it with intervals to ensure user stays within same application, which would work but in my opinion not optimal way.

So, I found that with SetWindowsHookExW() I can have event fired when foreground window is changed. But I am currently struggling with I need to pass into it. There is idhook which should be WH_CBT id of which is 5 as I research, also there are lpfn and hmod which I completely can't understand, and dwthreadid which should be 0 to capture events for all windows.

I tried to research other forums/docs but found nothing useful, besides some C# or C++ implementations which are pretty unfamiliar and I can't really port them into my Rust app. Any help will be appreciated!

Update: Thanks by this (How to use SetWindowsHookEx in Rust?)

I seem to figure out that lfpn param is for callback function which I setup successfully, but hmod as I understand in my case should be NULL, I'm passing that with std::ptr::null_mut(), which is causing next error:

the trait bound `*mut _: CanInto<HMODULE>` is not satisfied 
the following other types implement trait `CanInto<T>`:
  <DtdEntity as CanInto<IInspectable>>
  <DtdEntity as CanInto<IUnknown>>
  <DtdNotation as CanInto<IInspectable>>
  <DtdNotation as CanInto<IUnknown>>
  <HCURSOR as CanInto<HICON>>
  <IInspectable as CanInto<IUnknown>>
  <IXmlCharacterData as CanInto<IInspectable>>
  <IXmlCharacterData as CanInto<IUnknown>>
and 36 others
required for `*mut _` to implement `IntoParam<HMODULE, CopyType>
dalvi
  • 27
  • 5
  • Hard to get going, it requires DLL injection into every running process. Get ahead with [SetWinEventHook](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setwineventhook) to monitor for EVENT_SYSTEM_FOREGROUND – Hans Passant May 24 '23 at 13:32
  • @HansPassant, thank you! That's pretty useful comment! I can use it like that: `SetWindowsHookW(0x0003, Some(win_event_hook_callback))` It compiles! But sadly, it doesn't work for some reason. This function returns `HHOOK(0)` and that's it. When window is changed nothing happens here =(. I set up endless loop with `thread::sleep` so program won't finish after setting up this hook. Any thoughts? – dalvi May 24 '23 at 14:18
  • SetWindowsHookW??? Click the Ask Question button to properly document your new problem. – Hans Passant May 24 '23 at 14:20

0 Answers0