【问题标题】:c# intptr not getting handle时间:2019-05-10 标签:c#intptr没有得到句柄
【发布时间】:2018-06-27 14:13:56
【问题描述】:

我正在使用一些示例在 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);
        }
}

作为窗体应用程序:

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

            }
    }
    }

【问题讨论】:

  • 在调用表单的 Show() 方法之前,GUI 应用程序没有窗口。所以 init_connection() 运行得太快了,最早可能的时刻是 HandleCreated 事件。 Load 事件在它之后运行。 HandleCreated 也是您需要发现表单有不同句柄的事件,您需要知道,因为您的 COM 组件不能再正常工作。

标签: c# intptr


【解决方案1】:

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

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

handle = this.Handle;

【讨论】:

    猜你喜欢
    • 2020-06-15
    • 2020-10-01
    • 2015-06-14
    • 2011-07-08
    • 2012-02-03
    • 2017-04-15
    • 2021-07-31
    • 2016-01-27
    • 1970-01-01
    相关资源
    最近更新 更多