C#intptr没有得到处理

时间:2018-06-27 14:13:57

标签: c# intptr

我正在使用C#创建一个客户端,以使用一些示例连接到bopup。作为Windows应用程序运行时,句柄的值为0,而作为控制台应用程序运行时,值为> 0。为了使窗体内的主窗口句柄生效,我需要做些其他事情吗?

控制台:

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);
        }
}

作为Windows窗体应用程序:

 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());

            }
    }
    }

1 个答案:

答案 0 :(得分:1)

如果要使用当前表单的句柄,请使用Handle属性(this.Handle)。

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

handle = this.Handle;