asp.net-web-apiwindows-serviceshandletwain

Which handle should I use to initialize my scanner app


I wish to operate a scanner using a windows service hosting a web API. The reason I am doing so is to be able to operate the scanner from javascript using ajax and I do not wish to use ActiveX.

So I built a Windows Service hosting a Web API. I tried for the web API to start a scan application (had to bypass the UAC for this) but I run into a consistency issue (sometimes it worked and sometimes not).

So for now the controller of the web API has the code to start scanning built into it (instead of an external application). The problem is that I don`t have a handle to give the twain wrapper (it needs it for the windows message hook).

I tried to take the current process MainWindowHandle and even tried something silly as taking iexplore MainWindowHandle and I get an exception "Error initialising DSM".

As a twain library I use TwainDotNet

The code for doing is:

var p = Process.GetCurrentProcess();
_twain = new Twain(new WinFormsWindowMessageHook(p.MainWindowHandle));

Any idea on a good way to get a handle that will work? as I wrote above I ok with "stealing" another application handle if that will do the job (e.g. iexplore)

The exception is thrown from the TwainDotNet class DataSourceManager constructor in this code:

TwainResult result = Twain32Native.DsmParent(
            ApplicationId,
            IntPtr.Zero,
            DataGroup.Control,
            DataArgumentType.Parent,
            Message.OpenDSM,
            ref windowHandle);

if (result == TwainResult.Success)
{
    ...
}
else
{
    throw new TwainException("Error initialising DSM: " + result, result);
}

Thanks


Solution

  • Well I found an answer to this one. I used an ApplicationLoader class code from this URL.

    The code I use to get the good handle is:

    var processes = Process.GetProcessesByName("iexplore");
    if (processes.Length == 0)
    {
        WriteToLog("ScanController.Run GetProcessesByName returned 0 processes. Something went wrong!!!");
        return "ScanController.Run Failed: counlt not get handle to perform scan";
    }
    var p = processes[0];
    var hProcess = ApplicationLoader.OpenProcess(ApplicationLoader.MAXIMUM_ALLOWED, false, (uint)p.Id);
    

    Hope this will help someone.