c# intptr 没有得到句柄

c# intptr not getting handle

我正在使用一些示例在 C# 中创建客户端以连接到 bopup。当 运行 作为 windows 应用程序时,我得到的句柄值为 0,而当 运行 作为控制台应用程序时,我得到的值>0。是否需要做一些不同的事情才能在表单中获得主要的 window 句柄?

控制台:

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

            }
    }
    }

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

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

handle = this.Handle;