how to use http listner in windows forums c# app

manjunath 1 Reputation point
2020-12-16T08:04:45.15+00:00

Hi,

I am trying to convert twain(windows forums) into API using HTTP listener in windows forums. But my window keeps freezing. I believe my code is not sending event messages to a main window handle forum when a window is created on that thread when I wrote while loop. In application. run somewhere the message gets translated. But my while loop of httplistner is never sending any respones to them. I am complete beginneer in C# and searched online but couldnt figure out how to make this work. Any help is appreciated.

Any alternatives other than windows forums is appreciated too. I mainly want to capture the messagesof dll window handle created using imessagefilter to perform actions accordingly and couldnt find any other alternative in creating api other than window forums.

My code

 public Form1()  
        {  
            InitializeComponent();  
            winhwnd = this.Handle;  
            tw = new Twain();  
            tw.Init(winhwnd);  
        }  

when pressing button 1 httplistner gets executed. Could write below intialize component() but then again not sure why even form window disappears. I guess it has something to do with the while loop in app.run conflicting with my httplistner code

my library code

public void Init( IntPtr hwndp )  
{  
TwRC rc = DSMparent( appid, IntPtr.Zero, TwDG.Control, TwDAT.Parent, TwMSG.OpenDSM, ref hwndp );  
// by default twain_32. dll installed in every system so no exception needed  
if( rc == TwRC.Success )  
{  
rc = DSMident( appid, IntPtr.Zero, TwDG.Control, TwDAT.Identity, TwMSG.GetDefault, srcds );  
if (rc == TwRC.Success)  
hwnd = hwndp;  
else  
driver = "no twain driver";  
  }  
rc = DSMparent(appid, IntPtr.Zero, TwDG.Control, TwDAT.Parent, TwMSG.CloseDSM, ref hwndp);  
}  
  
  
public void Select()  
{  
TwRC rc;  
srcds = new TwIdentity();  
srcds.Id = IntPtr.Zero;  
rc = DSMparent(appid, IntPtr.Zero, TwDG.Control, TwDAT.Parent, TwMSG.OpenDSM, ref hwnd);  
rc = DSMident( appid, IntPtr.Zero, TwDG.Control, TwDAT.Identity, TwMSG.UserSelect, srcds );  
// default src is assigned during init phase  
// select changes the default if selected in list box  
if (rc == TwRC.Success) selected = srcds.ProductName; else selected = "not selected";  
rc = DSMparent(appid, IntPtr.Zero, TwDG.Control, TwDAT.Parent, TwMSG.CloseDSM, ref hwnd);  
}  
  
public void openDs()  
        {  
TwRC rc;  
rc = DSMparent(appid, IntPtr.Zero, TwDG.Control, TwDAT.Parent, TwMSG.OpenDSM, ref hwnd);  
rc = DSMident(appid, IntPtr.Zero, TwDG.Control, TwDAT.Identity, TwMSG.OpenDS, srcds);  
//TwCapability cap = new TwCapability(TwCap.XferCount, 1);  
//rc = DScap(appid, srcds, TwDG.Control, TwDAT.Capability, TwMSG.Set, cap);  
TwUserInterface guif = new TwUserInterface();  
guif.ShowUI = 1;  
guif.ModalUI = 0;  
guif.ParentHand = hwnd;  
rc = DSuserif(appid, srcds, TwDG.Control, TwDAT.UserInterface, TwMSG.EnableDS, guif);  
}  
  
my httplistner code  

  
  
public static void SimpleListenerExample(string[] prefixes)  
        {  
            if (!HttpListener.IsSupported)  
            {  
                Console.WriteLine("Windows XP SP2 or Server 2003 is required to use the HttpListener class.");  
                return;  
            }  
            // URI prefixes are required,  
            // for example "http://contoso.com:8080/index/".  
            if (prefixes == null || prefixes.Length == 0)  
                throw new ArgumentException("prefixes");  
  
            // Create a listener.  
            HttpListener listener = new HttpListener();  
            // Add the prefixes.  
            foreach (string s in prefixes)  
            {  
                listener.Prefixes.Add(s);  
            }  
            listener.Start();  
            
  
            while (true)  
            {  
                Console.WriteLine("Listening...");  
                // Note: The GetContext method blocks while waiting for a request.  
                HttpListenerContext context = listener.GetContext();  
                HttpListenerRequest request = context.Request;  
                // Obtain a response object.  
                HttpListenerResponse response = context.Response;  
  
                if (request.Url.ToString() == prefixes[0])  
                {  
                     
                    tw.Select();  
                    string responseString= null;  
                    // Construct a response.  
                    // by default list box selecting so no need  
                    if (tw.driver == "yes")  
                    {  
                        if (tw.selected != null)  
                        {  
                            responseString = "<HTML><BODY>Selected Device" + tw.selected + "</BODY></HTML>";  
                        }  
                        else  
                        {  
                            responseString = "<HTML><BODY>not selected any scanner</BODY></HTML>";  
                        }  
                    }  
                    else  
                    {  
                        responseString = "<HTML><BODY>no twain driver available</BODY></HTML>";  
  
                    }  
                    byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);  
                    // Get a response stream and write the response to it.  
                    response.ContentLength64 = buffer.Length;  
                    System.IO.Stream output = response.OutputStream;  
                    output.Write(buffer, 0, buffer.Length);  
                    // You must close the output stream.  
                    output.Close();  
                }  
  
                else if(request.Url.ToString() == prefixes[1])  
                {  
  
  
                    tw.openDs();  
                    string resp = "<HTML><BODY>ds selected</BODY></HTML>";  
                    byte[] buffer = System.Text.Encoding.UTF8.GetBytes(resp);  
                    // Get a response stream and write the response to it.  
                    response.ContentLength64 = buffer.Length;  
                    System.IO.Stream output = response.OutputStream;  
                    output.Write(buffer, 0, buffer.Length);  
                    // You must close the output stream.  
                    output.Close();  
                }  
  
                else  
                {  
                    response.StatusCode = 404;  
                    response.StatusDescription = "NOT FOUND";  
                    response.Close();  
                }  
                //listener.Stop();  
            }  
        }  
  
  private void button1_Click(object sender, EventArgs e)  
        {  
              
            string[] urls;  
            urls = new string[2] { "http://localhost:8888/select/", "http://localhost:8888/opends/" };  
            SimpleListenerExample(urls);  
  
        }  

The select works fine but open ds doesnt. basically my program loads up twain_32. dll. it takes main window handle so that it can send back event messages interacted with window. P.s I just created button 2 and button 3 to test select and opends functions and its working fine. But the problem appears when I try to fire up httplistner. So I believe the problem lies in while loop conflicting with application.run (form1) while loop somewhere and not sure how to fix this or write one. No basics just learning stuff online and couldnt find how to solve this

48589-capture0.png48510-capture.png

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,917 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Viorel 117.3K Reputation points
    2020-12-16T10:01:51.24+00:00

    Probably the form cannot respond to other commands since it is in infinite loop.

    Try moving SimpleListenerExample to a thread (in button1_Click):

    var t = new Thread( ( ) => SimpleListenerExample( urls ) ) { IsBackground = true };
    t.Start( );
    

    Why do you need the listener? (To access some details from local browser?). If the forms belong to the same program, you can simply call some forms’ functions.


  2. Timon Yang-MSFT 9,591 Reputation points
    2020-12-22T09:50:44.407+00:00

    For the InvalidOperationException in the picture, you can use Control.Invoke Method to solve it.

                this.Invoke((MethodInvoker)delegate ()  
                {  
                    this.Enabled = false;  
                });  
    

    We cannot perform certain operations on the UI thread from another thread.


    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.