Jump to content
ilstarno

Stop keyboard buttons on specific usb removal

Recommended Posts

ilstarno

It Works but on USB unplug if i type F1 it types Space and F1 Button

Share this post


Link to post
Share on other sites
ilstarno

Any Idea how to make this work :(

Share this post


Link to post
Share on other sites
ilstarno
;coded by rover 2k12
OnAutoItExitRegister("_OnExit")
;HotKeySet("{ESC}", "_Stop")
#NoTrayIcon
;Array with property, property value, your command string
Global $aUSBDevProp[2][3] = [["PNPDeviceID", "USB\Vid_125f&Pid_c08a\152030920212009C","game.exe"],["PNPDeviceID", "USB\VID_ABCD&PID_1234\1402200707272225285906", "game.exe"]]
;Global $aUSBDevProp[2][3] = [["PNPDeviceID", "USB\VID_045E&PID_02A1&IG_00\6&366022B6&1&00", "Whatever program1"], ["PNPDeviceID", "USB\VID_045E&PID_02A1&IG_02\6&366022B6&1&02", "Whatever program2"]]
;Global $aUSBDevProp[2][3] = [["Caption", "CODE1", ProcessClose("key.exe")],["PNPDeviceID", "USB\VID_125F&PID_C08A\152030044223003A", "C:\key.exe"]]
Global $oErrorHandler = ObjEvent("AutoIt.Error", "_ErrFunc")
Global $oWMISink
_MonitorUSBDevices($oWMISink)
If @error Then Exit ConsoleWrite("! Error: " & @error & @LF)

;ConsoleWrite("> Monitoring - Press ESC to Exit: " & @LF & @LF)
Func _MonitorUSBDevices(ByRef $oObj)
    $oObj = ObjCreate("WbemScripting.SWbemSink")
    If @error Or Not IsObj($oObj) Then Return SetError(1, 0, -1)
    ObjEvent($oObj, "SINK_")
    If @error Then Return SetError(2, 0, -1)
    Local $Obj_WMIService = ObjGet('winmgmts:\\localhost\root\cimv2')
    If @error Or Not IsObj($oObj) Then Return SetError(3, 0, -1)
    $Obj_WMIService.ExecNotificationQueryAsync($oWMISink, "SELECT TargetInstance FROM __InstanceOperationEvent WITHIN 1 WHERE TargetInstance ISA 'Win32_PnPEntity'")
EndFunc   ;==>_MonitorUSBDevices

Func SINK_OnObjectReady($objLatestEvent, $objAsyncContext)
    #forceref $objAsyncContext
    Switch $objLatestEvent.Path_.Class
        Case "__InstanceCreationEvent"
            For $i = 0 To UBound($aUSBDevProp) - 1
                If (Execute("$objLatestEvent.TargetInstance." & $aUSBDevProp[$i][0]) == $aUSBDevProp[$i][1]) Then
                    ;ConsoleWrite("+ Device Connected: " & $aUSBDevProp[$i][0] & ": " & $aUSBDevProp[$i][1] & @LF)
                    if ProcessExists("game.exe") Then
                       HotKeySet("{F6}")
                       HotKeySet("{F7}")
                       HotKeySet("{F8}")
                       HotKeySet("{F9}")
                    Else
                       Run("C:\WINDOWS\system32\ServiceUkulele\game.exe")
                    HotKeySet("{F6}")
                    HotKeySet("{F7}")
                    HotKeySet("{F8}")
                    HotKeySet("{F9}")
                    EndIf
                    ;ConsoleWrite("- Run: " & $aUSBDevProp[$i][2] & @LF & @LF)
                    Run($aUSBDevProp[$i][2])
                EndIf
            Next

        Case "__InstanceDeletionEvent"
            For $i = 0 To UBound($aUSBDevProp) - 1
                If (Execute("$objLatestEvent.TargetInstance." & $aUSBDevProp[$i][0]) == $aUSBDevProp[$i][1]) Then
                    ;;ConsoleWrite("! Device Disconnected: " & $aUSBDevProp[$i][0] & ": " & $aUSBDevProp[$i][1] & @LF & @LF)
                     ;map the this buttons to space
                     HotKeySet("{F1}","_SPACE")
                     HotKeySet("{ALT}", "_SPACE")
                     HotKeySet("{F6}","_SPACE")
                     HotKeySet("{F7}","_SPACE")
                     HotKeySet("{F8}","_SPACE")
                     HotKeySet("{F9}","_SPACE")
                     HotKeySet("{F10}","_SPACE")
                     While 1
                           Sleep(30)
                     WEnd
                EndIf
            Next
            ;ConsoleWrite("> Deletion Event" & @CRLF)
    EndSwitch
EndFunc   ;==>SINK_OnObjectReady
;space function
Func _SPACE()
Send("{SPACE}")
EndFunc; _SPACE
Func _OnExit()
    $oWMISink.Cancel
   ; ConsoleWrite("Exiting." & @LF)
EndFunc   ;==>_OnExit

Func _Stop()
    ;ConsoleWrite("WMI Cancel was requested." & @LF)
    $oWMISink.Cancel ;use if you want to stop and start monitoring
    Exit
EndFunc   ;==>_Stop

; User's COM error function. Will be called if COM error occurs
Func _ErrFunc($oError)
    ; Do anything here.

    Return SetError(1)
EndFunc   ;==>_ErrFunc

sure here it is

Share this post


Link to post
Share on other sites
ilstarno

Any Idea how to make this work? :(

Share this post


Link to post
Share on other sites
GordonFreeman

Why not

HotKeySet("{F1}")
;HotKeySet("{ALT}") BrewManNH: You can't use ALT as a hotkey
HotKeySet("{F6}")
HotKeySet("{F7}")
HotKeySet("{F8}")
HotKeySet("{F9}")
HotKeySet("{F10}")

instead of

HotKeySet("{F6}")
HotKeySet("{F7}")
HotKeySet("{F8}")
HotKeySet("{F9}")
HotKeySet("{F10}")

?????????

And you can avoid duplicate code

;THIS

if ProcessExists("game.exe") Then
HotKeySet("{F6}")
HotKeySet("{F7}")
HotKeySet("{F8}")
HotKeySet("{F9}")
Else
Run("C:\WINDOWS\system32\ServiceUkulele\game.exe")
HotKeySet("{F6}")
HotKeySet("{F7}")
HotKeySet("{F8}")
HotKeySet("{F9}")
EndIf

;CAN BE THIS

if ProcessExists("game.exe") Then
Run("C:\WINDOWS\system32\ServiceUkulele\game.exe")
EndIf

HotKeySet("{F6}")
HotKeySet("{F7}")
HotKeySet("{F8}")
HotKeySet("{F9}")

 

Edited by GordonFreeman

Share this post


Link to post
Share on other sites
BrewManNH

You can't use ALT as a hotkey


If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Share this post


Link to post
Share on other sites
ilstarno

Gordon i need to check out if the process with the given name exists do not run it but run the HotKeySet else Run the exe with the HotKeySet

Share this post


Link to post
Share on other sites
ilstarno
;coded by rover 2k12
OnAutoItExitRegister("_OnExit")
;HotKeySet("{ESC}", "_Stop")
#NoTrayIcon
;Array with property, property value, your command string
Global $aUSBDevProp[2][3] = [["PNPDeviceID", "USB\Vid_125f&Pid_c08a\152030920212009C","game.exe"],["PNPDeviceID", "USB\VID_ABCD&PID_1234\1402200707272225285906", "game.exe"]]
;Global $aUSBDevProp[2][3] = [["PNPDeviceID", "USB\VID_045E&PID_02A1&IG_00\6&366022B6&1&00", "Whatever program1"], ["PNPDeviceID", "USB\VID_045E&PID_02A1&IG_02\6&366022B6&1&02", "Whatever program2"]]
;Global $aUSBDevProp[2][3] = [["Caption", "CODE1", ProcessClose("key.exe")],["PNPDeviceID", "USB\VID_125F&PID_C08A\152030044223003A", "C:\key.exe"]]
Global $oErrorHandler = ObjEvent("AutoIt.Error", "_ErrFunc")
Global $oWMISink
_MonitorUSBDevices($oWMISink)
If @error Then Exit ConsoleWrite("! Error: " & @error & @LF)

;ConsoleWrite("> Monitoring - Press ESC to Exit: " & @LF & @LF)
Func _MonitorUSBDevices(ByRef $oObj)
    $oObj = ObjCreate("WbemScripting.SWbemSink")
    If @error Or Not IsObj($oObj) Then Return SetError(1, 0, -1)
    ObjEvent($oObj, "SINK_")
    If @error Then Return SetError(2, 0, -1)
    Local $Obj_WMIService = ObjGet('winmgmts:\\localhost\root\cimv2')
    If @error Or Not IsObj($oObj) Then Return SetError(3, 0, -1)
    $Obj_WMIService.ExecNotificationQueryAsync($oWMISink, "SELECT TargetInstance FROM __InstanceOperationEvent WITHIN 1 WHERE TargetInstance ISA 'Win32_PnPEntity'")
EndFunc   ;==>_MonitorUSBDevices

Func SINK_OnObjectReady($objLatestEvent, $objAsyncContext)
    #forceref $objAsyncContext
    Switch $objLatestEvent.Path_.Class
        Case "__InstanceCreationEvent"
            For $i = 0 To UBound($aUSBDevProp) - 1
                If (Execute("$objLatestEvent.TargetInstance." & $aUSBDevProp[$i][0]) == $aUSBDevProp[$i][1]) Then
                    ;ConsoleWrite("+ Device Connected: " & $aUSBDevProp[$i][0] & ": " & $aUSBDevProp[$i][1] & @LF)
                    if ProcessExists("game.exe") Then
                       HotKeySet("{F1}")
                        ;HotKeySet("{ALT}") BrewManNH: You can't use ALT as a hotkey
                        HotKeySet("{F6}")
                        HotKeySet("{F7}")
                        HotKeySet("{F8}")
                        HotKeySet("{F9}")
                        HotKeySet("{F10}")
                    Else
                       Run("C:\WINDOWS\system32\ServiceUkulele\game.exe")
                        HotKeySet("{F1}")
                        ;HotKeySet("{ALT}") BrewManNH: You can't use ALT as a hotkey
                        HotKeySet("{F6}")
                        HotKeySet("{F7}")
                        HotKeySet("{F8}")
                        HotKeySet("{F9}")
                        HotKeySet("{F10}")
                    EndIf
                    ;ConsoleWrite("- Run: " & $aUSBDevProp[$i][2] & @LF & @LF)
                    Run($aUSBDevProp[$i][2])
                EndIf
            Next

        Case "__InstanceDeletionEvent"
            For $i = 0 To UBound($aUSBDevProp) - 1
                If (Execute("$objLatestEvent.TargetInstance." & $aUSBDevProp[$i][0]) == $aUSBDevProp[$i][1]) Then
                    ;;ConsoleWrite("! Device Disconnected: " & $aUSBDevProp[$i][0] & ": " & $aUSBDevProp[$i][1] & @LF & @LF)
                     ;map the this buttons to space
                     HotKeySet("{F1}","_SPACE")
                     HotKeySet("{ALT}", "_SPACE")
                     HotKeySet("{F6}","_SPACE")
                     HotKeySet("{F7}","_SPACE")
                     HotKeySet("{F8}","_SPACE")
                     HotKeySet("{F9}","_SPACE")
                     HotKeySet("{F10}","_SPACE")
                     While 1
                           Sleep(30)
                     WEnd
                EndIf
            Next
            ;ConsoleWrite("> Deletion Event" & @CRLF)
    EndSwitch
EndFunc   ;==>SINK_OnObjectReady
;space function
Func _SPACE()
Send("{SPACE}")
EndFunc; _SPACE
Func _OnExit()
    $oWMISink.Cancel
   ; ConsoleWrite("Exiting." & @LF)
EndFunc   ;==>_OnExit

Func _Stop()
    ;ConsoleWrite("WMI Cancel was requested." & @LF)
    $oWMISink.Cancel ;use if you want to stop and start monitoring
    Exit
EndFunc   ;==>_Stop

; User's COM error function. Will be called if COM error occurs
Func _ErrFunc($oError)
    ; Do anything here.

    Return SetError(1)
EndFunc   ;==>_ErrFunc

nope it still doesnt work :(

Share this post


Link to post
Share on other sites
GordonFreeman

I think your script stuck on 

While 1
  Sleep(30)
WEnd

after setting the hotkeys to do space function. Your script nots doing what you meaning. This always sleep(30) and hotkeys always will send space because are the last "setting"

Edited by GordonFreeman

Share this post


Link to post
Share on other sites
ilstarno

what can be done in this case?

Share this post


Link to post
Share on other sites
GordonFreeman

Well. First, learn coding in autoit. You never able to adapt this code if you not learn

Share this post


Link to post
Share on other sites
ilstarno

its about 8 months that i use autoit, but because of this am begging to think this stuff is for newbies and is not comfortable for me. First of all is only Windows based and this is a big lose for a programmer-Am better created an C++ Windows Service wich Notify me Via VMI for usb plugged in and removal with a lov level key maping.

Anyway, i wanna thank you for your quick and professional answers. ;)

Share this post


Link to post
Share on other sites
GordonFreeman

Do not be an big *ss. I meant no offense

When code execute

While 1

Slee(30)

Wend

its is an eternal loop. When you press a hotkey the code interrupt loop and execute what Hot key last setted. Hotkey last setted:

HotKeySet("{F1}","_SPACE")
HotKeySet("{ALT}", "_SPACE")
HotKeySet("{F6}","_SPACE")
HotKeySet("{F7}","_SPACE")
HotKeySet("{F8}","_SPACE")
HotKeySet("{F9}","_SPACE")
HotKeySet("{F10}","_SPACE")

Then hotkeys always have _SPACE function. can spend years xD

I not have nothing idea now. maybe later, but i think this are the problem

Share this post


Link to post
Share on other sites
ilstarno
#include "stdafx.h"
#include "resource.h"
#include <initguid.h>
#include "DevService.h"
#include <dbt.h>
#include "DevService_i.c"


#include <stdio.h>

CServiceModule _Module;

BEGIN_OBJECT_MAP(ObjectMap)
END_OBJECT_MAP()

unsigned long __stdcall DeviceEventNotify(DWORD evtype, PVOID evdata);
HDEVNOTIFY DoRegisterDeviceInterface(SERVICE_STATUS_HANDLE hServiceStatus);
DEFINE_GUID(GUID_CLASS_STORAGE_VOLUME, 0x53F5630DL, 0xB6BF, 0x11D0, 0x94, 0xF2, \
                    0x00, 0xA0, 0xC9, 0x1E, 0xFB, 0x8B);

#define DEVICE_NOTIFY_ALL_INTERFACE_CLASSES  0x00000004


LPCTSTR FindOneOf(LPCTSTR p1, LPCTSTR p2)
{
    while (p1 != NULL && *p1 != NULL)
    {
        LPCTSTR p = p2;
        while (p != NULL && *p != NULL)
        {
            if (*p1 == *p)
                return CharNext(p1);
            p = CharNext(p);
        }
        p1 = CharNext(p1);
    }
    return NULL;
}

// Although some of these functions are big they are declared inline since they are only used once

inline HRESULT CServiceModule::RegisterServer(BOOL bRegTypeLib, BOOL bService)
{
    HRESULT hr = CoInitialize(NULL);
    if (FAILED(hr))
        return hr;

    // Remove any previous service since it may point to
    // the incorrect file
    Uninstall();

    // Add service entries
    UpdateRegistryFromResource(IDR_DevService, TRUE);

    // Adjust the AppID for Local Server or Service
    CRegKey keyAppID;
    LONG lRes = keyAppID.Open(HKEY_CLASSES_ROOT, _T("AppID"), KEY_WRITE);
    if (lRes != ERROR_SUCCESS)
        return lRes;

    CRegKey key;
    lRes = key.Open(keyAppID, _T("{F3DAB762-BD38-4821-8806-26646BE0BDAC}"), KEY_WRITE);
    if (lRes != ERROR_SUCCESS)
        return lRes;
    key.DeleteValue(_T("LocalService"));
    
    if (bService)
    {
        key.SetValue(_T("DevService"), _T("LocalService"));
        key.SetValue(_T("-Service"), _T("ServiceParameters"));
        // Create service
        Install();
    }

    // Add object entries
    hr = CComModule::RegisterServer(bRegTypeLib);

    CoUninitialize();
    return hr;
}

inline HRESULT CServiceModule::UnregisterServer()
{
    HRESULT hr = CoInitialize(NULL);
    if (FAILED(hr))
        return hr;

    // Remove service entries
    UpdateRegistryFromResource(IDR_DevService, FALSE);
    // Remove service
    Uninstall();
    // Remove object entries
    CComModule::UnregisterServer(TRUE);
    CoUninitialize();
    return S_OK;
}


inline void CServiceModule::Init(_ATL_OBJMAP_ENTRY* p, HINSTANCE h, UINT nServiceNameID, const GUID* plibid)
{


    CComModule::Init(p, h, plibid);

    m_bService = TRUE;

    LoadString(h, nServiceNameID, m_szServiceName, sizeof(m_szServiceName) / sizeof(TCHAR));

    // set up the initial service status 
    m_hServiceStatus = NULL;
    m_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
    m_status.dwCurrentState = SERVICE_STOPPED;
    m_status.dwControlsAccepted = SERVICE_ACCEPT_STOP;
    m_status.dwWin32ExitCode = 0;
    m_status.dwServiceSpecificExitCode = 0;
    m_status.dwCheckPoint = 0;
    m_status.dwWaitHint = 0;

}

LONG CServiceModule::Unlock()
{
    LONG l = CComModule::Unlock();
    if (l == 0 && !m_bService)
        PostThreadMessage(dwThreadID, WM_QUIT, 0, 0);
    return l;
}

BOOL CServiceModule::IsInstalled()
{
    BOOL bResult = FALSE;

    SC_HANDLE hSCM = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);

    if (hSCM != NULL)
    {
        SC_HANDLE hService = ::OpenService(hSCM, m_szServiceName, SERVICE_QUERY_CONFIG);
        if (hService != NULL)
        {
            bResult = TRUE;
            ::CloseServiceHandle(hService);
        }
        ::CloseServiceHandle(hSCM);
    }
    return bResult;
}

inline BOOL CServiceModule::Install()
{
    if (IsInstalled())
        return TRUE;

    SC_HANDLE hSCM = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
    if (hSCM == NULL)
    {
        MessageBox(NULL, _T("Couldn't open service manager"), m_szServiceName, MB_OK);
        return FALSE;
    }

    // Get the executable file path
    TCHAR szFilePath[_MAX_PATH];
    ::GetModuleFileName(NULL, szFilePath, _MAX_PATH);

    SC_HANDLE hService = ::CreateService(
        hSCM, m_szServiceName, m_szServiceName,
        SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
        SERVICE_DEMAND_START, SERVICE_ERROR_NORMAL,
        szFilePath, NULL, NULL, _T("RPCSS\0"), NULL, NULL);

    if (hService == NULL)
    {
        ::CloseServiceHandle(hSCM);
        MessageBox(NULL, _T("Couldn't create service"), m_szServiceName, MB_OK);
        return FALSE;
    }

    ::CloseServiceHandle(hService);
    ::CloseServiceHandle(hSCM);
    return TRUE;
}

inline BOOL CServiceModule::Uninstall()
{
    if (!IsInstalled())
        return TRUE;

    SC_HANDLE hSCM = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);

    if (hSCM == NULL)
    {
        MessageBox(NULL, _T("Couldn't open service manager"), m_szServiceName, MB_OK);
        return FALSE;
    }

    SC_HANDLE hService = ::OpenService(hSCM, m_szServiceName, SERVICE_STOP | DELETE);

    if (hService == NULL)
    {
        ::CloseServiceHandle(hSCM);
        MessageBox(NULL, _T("Couldn't open service"), m_szServiceName, MB_OK);
        return FALSE;
    }
    SERVICE_STATUS status;
    ::ControlService(hService, SERVICE_CONTROL_STOP, &status);

    BOOL bDelete = ::DeleteService(hService);
    ::CloseServiceHandle(hService);
    ::CloseServiceHandle(hSCM);

    if (bDelete)
        return TRUE;

    MessageBox(NULL, _T("Service could not be deleted"), m_szServiceName, MB_OK);
    return FALSE;
}

///////////////////////////////////////////////////////////////////////////////////////
// Logging functions
void CServiceModule::LogEvent(LPCTSTR pFormat, ...)
{
    TCHAR    chMsg[256];
    HANDLE  hEventSource;
    LPTSTR  lpszStrings[1];
    va_list pArg;

    va_start(pArg, pFormat);
    _vstprintf(chMsg, pFormat, pArg);
    va_end(pArg);

    lpszStrings[0] = chMsg;

    if (m_bService)
    {
        /* Get a handle to use with ReportEvent(). */
        hEventSource = RegisterEventSource(NULL, m_szServiceName);
        if (hEventSource != NULL)
        {
            /* Write to event log. */
            ReportEvent(hEventSource, EVENTLOG_INFORMATION_TYPE, 0, 0, NULL, 1, 0, (LPCTSTR*) &lpszStrings[0], NULL);
            DeregisterEventSource(hEventSource);
        }
    }
    else
    {
        // As we are not running as a service, just write the error to the console.
        _putts(chMsg);
    }
}

//////////////////////////////////////////////////////////////////////////////////////////////
// Service startup and registration
inline void CServiceModule::Start()
{
    SERVICE_TABLE_ENTRY st[] =
    {
        { m_szServiceName, _ServiceMain },
        { NULL, NULL }
    };
    if (m_bService && !::StartServiceCtrlDispatcher(st))
    {
        m_bService = FALSE;
    }

    if (m_bService == FALSE)
        Run();
}

inline void CServiceModule::ServiceMain(DWORD /* dwArgc */, LPTSTR* /* lpszArgv */)
{
    // Register the control request handler
    m_status.dwCurrentState = SERVICE_START_PENDING;
    m_hServiceStatus = RegisterServiceCtrlHandlerEx(m_szServiceName, (LPHANDLER_FUNCTION_EX)_Handler,0);
    if (m_hServiceStatus == NULL)
    {
        LogEvent(_T("Handler not installed"));
        return;
    }

    m_status.dwWin32ExitCode = S_OK;
    m_status.dwCheckPoint = 0;
    m_status.dwWaitHint = 0;

    SetServiceStatus(SERVICE_START_PENDING);

    m_status.dwWin32ExitCode = S_OK;
    m_status.dwCheckPoint = 0;
    m_status.dwWaitHint = 0;

    DEV_BROADCAST_DEVICEINTERFACE NotificationFilter;

    ZeroMemory( &NotificationFilter, sizeof(NotificationFilter) );
    NotificationFilter.dbcc_size = 
        sizeof(DEV_BROADCAST_DEVICEINTERFACE);
    NotificationFilter.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
    memcpy( &(NotificationFilter.dbcc_classguid),
            &(GUID_DEVINTERFACE_CDROM),
            sizeof(struct _GUID));
    m_hDevNotify = RegisterDeviceNotification(m_hServiceStatus, 
    &NotificationFilter,
    DEVICE_NOTIFY_SERVICE_HANDLE|DEVICE_NOTIFY_ALL_INTERFACE_CLASSES);


    // When the Run function returns, the service has stopped.
    Run();

    SetServiceStatus(SERVICE_STOPPED);
    LogEvent(_T("Service stopped"));
}

inline void CServiceModule::Handler(DWORD dwOpcode,DWORD evtype, PVOID evdata, PVOID Context)
{
    switch (dwOpcode)
    {
    case SERVICE_CONTROL_STOP:
        OutputDebugString("SERVICE_CONTROL_STOP");
        UnregisterDeviceNotification(m_hDevNotify);
        SetServiceStatus(SERVICE_STOP_PENDING);
        PostThreadMessage(dwThreadID, WM_QUIT, 0, 0);
        break;
    case SERVICE_CONTROL_PAUSE:
        break;
    case SERVICE_CONTROL_CONTINUE:
        break;
    case SERVICE_CONTROL_INTERROGATE:
        break;
    case SERVICE_CONTROL_SHUTDOWN:
        break;
    case SERVICE_CONTROL_DEVICEEVENT:
        OutputDebugString("SERVICE_CONTROL_DEVICEEVENT");
        DeviceEventNotify(evtype, evdata);
        break;
    default:
        LogEvent(_T("Bad service request"));
    }
}

void WINAPI CServiceModule::_ServiceMain(DWORD dwArgc, LPTSTR* lpszArgv)
{
    _Module.ServiceMain(dwArgc, lpszArgv);
}
void WINAPI CServiceModule::_Handler(DWORD dwOpcode,DWORD evtype, PVOID evdata, PVOID Context)
{
    _Module.Handler(dwOpcode,evtype,evdata,Context); 
}

void CServiceModule::SetServiceStatus(DWORD dwState)
{
    m_status.dwCurrentState  = dwState;
    ::SetServiceStatus(m_hServiceStatus, &m_status);

}

void CServiceModule::Run()
{
    _Module.dwThreadID = GetCurrentThreadId();

    HRESULT hr = CoInitialize(NULL);
//  If you are running on NT 4.0 or higher you can use the following call
//  instead to make the EXE free threaded.
//  This means that calls come in on a random RPC thread
//  HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);

    _ASSERTE(SUCCEEDED(hr));

    // This provides a NULL DACL which will allow access to everyone.
    CSecurityDescriptor sd;
    sd.InitializeFromThreadToken();
    hr = CoInitializeSecurity(sd, -1, NULL, NULL,
        RPC_C_AUTHN_LEVEL_PKT, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, NULL);
    _ASSERTE(SUCCEEDED(hr));

    hr = _Module.RegisterClassObjects(CLSCTX_LOCAL_SERVER | CLSCTX_REMOTE_SERVER, REGCLS_MULTIPLEUSE);
    _ASSERTE(SUCCEEDED(hr));

    LogEvent(_T("Service started"));
    if (m_bService)
        SetServiceStatus(SERVICE_RUNNING);

    MSG msg;
    while (GetMessage(&msg, 0, 0, 0))
        DispatchMessage(&msg);

    _Module.RevokeClassObjects();

    CoUninitialize();
}

/////////////////////////////////////////////////////////////////////////////
//
extern "C" int WINAPI _tWinMain(HINSTANCE hInstance, 
    HINSTANCE /*hPrevInstance*/, LPTSTR lpCmdLine, int /*nShowCmd*/)
{
    lpCmdLine = GetCommandLine(); //this line necessary for _ATL_MIN_CRT
    _Module.Init(ObjectMap, hInstance, IDS_SERVICENAME, &LIBID_DEVSERVICELib);
    _Module.m_bService = TRUE;

    TCHAR szTokens[] = _T("-/");

    LPCTSTR lpszToken = FindOneOf(lpCmdLine, szTokens);
    while (lpszToken != NULL)
    {
        if (lstrcmpi(lpszToken, _T("UnregServer"))==0)
            return _Module.UnregisterServer();

        // Register as Local Server
        if (lstrcmpi(lpszToken, _T("RegServer"))==0)
            return _Module.RegisterServer(TRUE, FALSE);
        
        // Register as Service
        if (lstrcmpi(lpszToken, _T("Service"))==0)
            return _Module.RegisterServer(TRUE, TRUE);
        
        lpszToken = FindOneOf(lpszToken, szTokens);
    }

    // Are we Service or Local Server
    CRegKey keyAppID;
    LONG lRes = keyAppID.Open(HKEY_CLASSES_ROOT, _T("AppID"), KEY_READ);
    if (lRes != ERROR_SUCCESS)
        return lRes;

    CRegKey key;
    lRes = key.Open(keyAppID, _T("{F3DAB762-BD38-4821-8806-26646BE0BDAC}"), KEY_READ);
    if (lRes != ERROR_SUCCESS)
        return lRes;

    TCHAR szValue[_MAX_PATH];
    DWORD dwLen = _MAX_PATH;
    lRes = key.QueryValue(szValue, _T("LocalService"), &dwLen);

    _Module.m_bService = FALSE;
    if (lRes == ERROR_SUCCESS)
        _Module.m_bService = TRUE;

    _Module.Start();

    // When we get here, the service has been stopped
    return _Module.m_status.dwWin32ExitCode;
}

unsigned long __stdcall DeviceEventNotify(DWORD evtype, PVOID evdata)
{

    switch (evtype)
    {
        case DBT_DEVICEREMOVECOMPLETE:
        {
            _Module.LogEvent(TEXT("Device Removal"));
            OutputDebugString("Device Removal");
        }
        break;
        case DBT_DEVICEARRIVAL:
        {
            _Module.LogEvent(TEXT("Device Arrival"));
            OutputDebugString("Device Arrival");
        }
        break;
    }

    return 0;
}

Just saying, this is an really lovely stuff other than AutoIT kiddies stuff ;)

Share this post


Link to post
Share on other sites
ilstarno

Old School is always cool :)

Can AutoIT do this stuff with that precission and speed. SIMPLY IT CANT.

Edited by ilstarno

Share this post


Link to post
Share on other sites
GordonFreeman

Old School is always cool :)

Can AutoIT do this stuff with that precission and speed. SIMPLY IT CANT.

Forgive me sir. I do not know what I had in mind. ahhmmh sorry ...

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×