form1.cs
来自「清华大学出版社出版的 移动应用开发宝典 张大威(2008)的附书源代码」· CS 代码 · 共 84 行
CS
84 行
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace NamedEvents
{
public partial class Form1 : Form
{
private Chapter14.Threading.EventWaitHandle hQuit;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//event to kill the worker thread
hQuit = new Chapter14.Threading.EventWaitHandle(false, Chapter14.Threading.EventResetMode.AutoReset, null);
//setup the named events
Notify.RegisterNamedEvent(NotificationEvent.NetConnect, "NetConnected");
Notify.RegisterNamedEvent(NotificationEvent.NetDisconnect, "NetDisconnected");
System.Threading.Thread eventThread = new System.Threading.Thread(new System.Threading.ThreadStart(EventThread));
eventThread.IsBackground = true;
eventThread.Start();
}
private void Connected(object sender, EventArgs e)
{
this.BackColor = Color.Green;
}
private void Disconnected(object sender, EventArgs e)
{
this.BackColor = Color.Red;
}
private void EventThread()
{
Chapter14.Threading.EventWaitHandle hConnected = new Chapter14.Threading.EventWaitHandle(false, Chapter14.Threading.EventResetMode.AutoReset, "NetConnected");
Chapter14.Threading.EventWaitHandle hDisconnected = new Chapter14.Threading.EventWaitHandle(false, Chapter14.Threading.EventResetMode.AutoReset, "NetDisconnected");
while (true)
{
int eventIndex = Chapter14.Threading.EventWaitHandle.WaitAny(new System.Threading.WaitHandle[] { hQuit, hConnected, hDisconnected });
switch (eventIndex)
{
case 0:
hConnected.Close();
hDisconnected.Close();
hQuit.Close();
return;
case 1:
//we are on a background thread so invoke
Invoke(new EventHandler(Connected));
break;
case 2:
Invoke(new EventHandler(Disconnected));
break;
}
}
}
private void Form1_Closing(object sender, CancelEventArgs e)
{
//stop the system raising these events
Notify.UnregisterNamedEvent("NetConnected");
Notify.UnregisterNamedEvent("NetDisconnected");
//signal our control event to close background thread
hQuit.Set();
}
}
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?