【发布时间】: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 组件不能再正常工作。