C#控制台应用程序+事件处理 [英] C# Console App + Event Handling
问题描述
STA线程
的基本要求是需要运行消息
pump。在Windows窗体中,您可以使用
Application.Run。或者你可以用
user32!GetMessage& amp; DispatchMessage函数。
但是在WinForms或WPF中使用
可能更容易。
程序使用user32 - > GetMessage& user32 - > DispatchMessage?
请参阅MSDN中的使用消息和消息队列主题(Win32和COM开发>用户界面> Windows用户体验> Windows管理> Windows用户界面>窗口>消息和消息队列;您可能需要查看同一部分中的其他文章和示例。快速总结,省略错误处理和使用C语法而不是C#,原因如下:
RegisterClass(...);
CreateWindow(...);
ShowWindow(...); //可能不在你的情况下
while(GetMessage(& msg,NULL,0,0)){
TranslateMessage(& msg);
DispatchMessage(& msg);
}
从窗口设置样板中可以看出,这仍然依赖于沉默窗口,尽管通过Win32 API创建和消息抽取,而不是通过WinForms。所以你不是真的在这样做得到什么。因此,我的感觉是将这些东西翻译成C#没有太多的意义 - 如果你的问题的唯一解决方案是一个不可见的窗口,你可以使用一个看不见的Windows窗体和这个平台附带的所有友好的包装器。
但是,如果您没有真正使用Windows Forms控件(如链接问题的海报),那么您可以非常高兴地在控制台应用程序中使用.NET事件。对STA的限制和消息抽取的需要特定于从WinForms和ActiveX控件(如WebBrowser)接收事件(或来自Win32 HWND的消息,尽管不一定要求STA)。
Hey all. I'm trying to see about handling events in a console application. I would prefer to not use silent WinForms (though I understand that that's one way) to do it. I've read over a similar question and its response. See response text below (link):
The basic requirement of an STA thread is that it needs to run a message pump. In Windows Forms, you can use Application.Run. Or you could write the message pump by hand, using user32!GetMessage & DispatchMessage. But it's probably easier to use the one in WinForms or WPF.
What the basic structure of a program that uses "user32 -> GetMessage" & "user32 -> DispatchMessage"?
See the topic "Using Messages and Message Queues" in MSDN (under Win32 and COM Development > User Interface > Windows User Experience > Windows Management > Windows User Interface > Windowing > Messages and Message Queues; you'll probably need to take a look at the other articles and samples in the same section). Quick summary, omitting error handling and using C syntax rather than C# for reasons discussed below:
RegisterClass(...);
CreateWindow(...);
ShowWindow(...); // probably not in your case
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
As you can see from the window setup boilerplate, this still relies on "silent windows," albeit created and message-pumped via the Win32 API rather than through WinForms. So you're not really gaining anything by doing this way. Hence my feeling there's not much point translating this stuff into C# -- if the only solution to your problem is an invisible window, you may as well use an invisible Windows Form and all the friendly wrappers that come with that platform.
However, if you're not actually using a Windows Forms control like the poster of the linked question, then you can quite happily use .NET events in a console application. The restriction to STA and the need for a message pump is specific to receiving events from WinForms and ActiveX controls like the WebBrowser (or messages from Win32 HWNDs, though that doesn't necessarily require STA).
这篇关于C#控制台应用程序+事件处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!