从 C# 创建 Win32 事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/447546/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating Win32 events from c#
提问by ofer
I'd like create a kernel(aka named events) from C#.
我想从 C# 创建一个内核(又名命名事件)。
Do I have to interop services and wrap the native CreateEvent function or is there already a .NET class that does the job?
我是否必须互操作服务并包装本机 CreateEvent 函数,或者是否已经有一个 .NET 类可以完成这项工作?
The function that I need to run should be something like this: hEvent = CreateEvent ( NULL , false , false , "MyCSHARPEvent" );
我需要运行的函数应该是这样的: hEvent = CreateEvent ( NULL , false , false , "MyCSHARPEvent" );
This should notify all procs that probing forMyCSHARPEvent about the event.
这应该通知所有探测 forMyCSHARPEvent 事件的进程。
If there is a need to wrap the function, how would I translate the SECURITY_ATTRIBUTES struct from C# to win32?
如果需要包装函数,我将如何将 SECURITY_ATTRIBUTES 结构从 C# 转换为 win32?
采纳答案by Stu Mackellar
Take a look at the EventWaitHandleclass. It's supported from .Net 2.0 onwards and allows creation of named events. It also supports setting event security, depending on which constructor you use.
查看EventWaitHandle类。从 .Net 2.0 开始支持它,并允许创建命名事件。它还支持设置事件安全性,具体取决于您使用的构造函数。
回答by scottm
If you still want to use interop, you can define the function like this:
如果你仍然想使用互操作,你可以像这样定义函数:
[DllImport("kernel32.dll")]
static extern IntPtr CreateEvent(IntPtr lpEventAttributes, bool bManualReset, bool bInitialState, string lpName);
and the struct like this(you may have to mess with the Pack attribute to make it fit):
和这样的结构(你可能不得不弄乱 Pack 属性以使其适合):
[StructLayout(LayoutKind.Sequential)]
struct SECURITY_ATTRIBUTES{
public int length;
public IntPtr securityDesc;
public bool inherit;
}
Also, here's a code exampleof putting it all together.
此外,这里有一个将它们组合在一起的代码示例。