Search code examples
c#intptr

c# intptr not getting handle


I'm creating a client in C# to connnect to bopup using some examples. I'm getting a 0 value for the handle when running as windows application whereas getting a value>0 when running as console application. Is there something I have to do different to get the main window handle within the form?

Console:

static void Main(string[] args)
    {
        string error = null;
        uint refResult = 0;

        CSCLIENTLib.ServerClientVB client = new CSCLIENTLib.ServerClientVB();

        try
        {
            IntPtr handle = Process.GetCurrentProcess().MainWindowHandle;

            string server = "localhost";
     //       Console.WriteLine(server + "|" + 0 + "|" + (byte)VBClientType.Messenger + "|" + (uint)handle + "|" + refResult);
            client.Initialize(server, 0, (byte)VBClientType.Messenger, (uint)handle, ref refResult);


        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());

            client.GetEventDescription(refResult, ref error);
            Console.WriteLine(error);
        }
}

As windows form application:

 public partial class Form1 : Form
    {
       string error = null;
       uint refResult = 0;
        private static CSCLIENTLib.ServerClientVB client;
        IntPtr handle;

        public Form1()
        {
            InitializeComponent();

            init_connection();
        }

  private void init_connection()
        {
            client = new CSCLIENTLib.ServerClientVB();
            try
            {
                handle = Process.GetCurrentProcess().MainWindowHandle;
                string server = "localhost";
                MessageBox.Show(server + "|" + 0 + "|" + (byte)VBClientType.Messenger + "|" + (uint)handle + "|" + refResult);
                client.Initialize(server, 0, (byte)VBClientType.Messenger, (uint)handle, ref refResult);
            }
            catch (Exception ex)
            {
                // Console.WriteLine(ex.ToString());
                MessageBox.Show("ERROR: " + ex.ToString());
                client.GetEventDescription(refResult, ref error);
                // Console.WriteLine(error);
                MessageBox.Show("ERROR: " + error.ToString());

            }
    }
    }

Solution

  • If you want the handle for the current form, use the Handle property (this.Handle).

    https://msdn.microsoft.com/en-us/library/system.windows.forms.control.handle(v=vs.110).aspx

    handle = this.Handle;