private void btnStartStop_Click(object sender, EventArgs e) { // do stuff depending on the text switch (btnStartStop.Text) { case "Start": { // create a new Messages object and pass it into the PowerNotifications // constructor MessageList = new Messages(); // create the powernotifications object pn = new PowerNotifications(ref MessageList); pn.Start(); // start a timer to monitor the messages queue if (timer1 == null) timer1 = new System.Windows.Forms.Timer(); timer1.Interval = 250; timer1.Tick += new EventHandler(ReadText); timer1.Enabled = true; btnStartStop.Text = "Stop"; } break; case "Stop": // stop the thread pn.Stop(); lstInfo.Items.Add("(" + System.DateTime.Now.ToString("hh:mm:ss") + ") stopping loop"); timer1.Enabled = false; btnStartStop.Text = "Start"; break; default: break; } }
// Overloaded constructor that accepts a reference to the // Messages object created by the form. public PowerNotifications(ref Messages mList) { // assign the messages object MessageList = mList; // set up the Message queue options, create the queue // and create a background thread to monitor it MsgQOptions options = new MsgQOptions(); options.dwFlags = 0; options.dwMaxMessages = 20; options.cbMaxMessage = 10000; options.bReadAccess = true; options.dwSize = (uint)System.Runtime.InteropServices.Marshal.SizeOf(options); ptr = CreateMsgQueue("Test", ref options); IntPtr ptr2 = RequestPowerNotifications(ptr, 0xFFFFFFFF); if (ptr2.Equals(IntPtr.Zero)) { // error occurred MessageList.AddMessage("Error with RPN"); } t = new Thread(new ThreadStart(DoWork)); }