ActivateClient Alternative

Posted by Morat on Fri 15 Jan 2010 06:58 PM — 1 posts, 11,360 views.

#0
You may have noticed that when you try and bring MUSHclient to the foreground using the function ActivateClient that it just flashes the taskbar button a few times.

I wrote some c code for a dll that does the following:
  • test if MUSHclient is in the foreground (use to trigger a sound when in another window)
  • set MUSHclient as the foreground window instead of flashing the taskbar button
focus.c

#pragma comment(lib, "lua5.1.lib")

#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
#include "luaconf.h"

#include <windows.h>

static int get_foreground_window(lua_State *L)
  {
  HWND hForeground = GetForegroundWindow();
  lua_pushlightuserdata(L, hForeground);
  return 1;
  }

static int set_foreground_window(lua_State *L)
  {
  HWND hForeground = GetForegroundWindow();
  HWND hMUSHclient = lua_touserdata(L, 1);
  DWORD hForegroundId = GetWindowThreadProcessId(hForeground, NULL);
  DWORD hMUSHclientId = GetWindowThreadProcessId(hMUSHclient, NULL);
  AttachThreadInput(hForegroundId, hMUSHclientId, 1); /* attach */
  SetForegroundWindow(hMUSHclient);
  AttachThreadInput(hForegroundId, hMUSHclientId, 0); /* detach */
  if (IsIconic(hMUSHclient))
    ShowWindow(hMUSHclient, SW_RESTORE);
  else
    ShowWindow(hMUSHclient, SW_SHOW);
  return 0;
  }

static const luaL_reg focuslib[] = 
{
  {"get_foreground_window", get_foreground_window},
  {"set_foreground_window", set_foreground_window},
  {NULL, NULL}
};

LUALIB_API int __declspec(dllexport) luaopen_focus(lua_State *L)
 {
  luaL_openlib(L, "focus", focuslib, 0);
  return 1;
 }
build files:

focus.c
lua.h
lualib.h
lauxlib.h
luaconf.h
lua5.1.lib
lua5.1.dll

http://www.gammon.com.au/files/mushclient/lua5.1_extras/lua5.1_lib.zip

build command using MinGW (GCC):
gcc -shared -o focus.dll focus.c -L.\ -llua5.1
I'm using MinGW (GCC) from Bloodshed Dev-C++ 5.0 Beta 9.2 (4.9.9.2) with MinGW/GCC 3.4.2.

http://www.bloodshed.net/dev/devcpp.html

script examples:
assert(package.loadlib("focus.dll", "luaopen_focus"))()
if focus.get_foreground_window() == GetFrame() then
  print("foreground window is MUSHclient")
else
  print("foreground window is not MUSHclient")
end
assert(package.loadlib("focus.dll", "luaopen_focus"))()
if focus.get_foreground_window() ~= GetFrame() then
  Sound("C:/WINDOWS/Media/notify.wav")
end
assert(package.loadlib("focus.dll", "luaopen_focus"))()
focus.set_foreground_window(GetFrame())
reference:

Extending Lua scripting with your own code
http://www.gammon.com.au/forum/?id=4915

Launching Apps in the Foreground
http://www.ddj.com/windows/184405755