Beispiel #1
0
        public static void PlayTone(Tone[] tones)
        {
            WAVEFORMAT_MIDI wfm = new WAVEFORMAT_MIDI();

            wfm.WAVEFORMATEX.FormatTag  = FormatTag.MIDI;
            wfm.WAVEFORMATEX.Channels   = 1;
            wfm.WAVEFORMATEX.BlockAlign = 8; // sizeof(WAVEFORMAT_MIDI_MESSAGE);
            wfm.WAVEFORMATEX.Size       = WAVEFORMAT_MIDI_EXTRASIZE;

            // trial & error seems to be the way to get this - tested using an Axim x51
            // maybe expose these if it varies from hardware to hardware
            wfm.USecPerQuarterNote  = 100000;
            wfm.TicksPerQuarterNote = 15;

            IntPtr          hWaveOut;
            EventWaitHandle hEvent = new EventWaitHandle(false, EventResetMode.ManualReset);

            byte[] d = wfm.GetBytes();

            int result = WaveAudio.NativeMethods.waveOutOpen(out hWaveOut, 0, d, hEvent.Handle, 0, CALLBACK_EVENT);

            Audio.CheckWaveError(result);

            WAVEFORMAT_MIDI_MESSAGE[] messages = new WAVEFORMAT_MIDI_MESSAGE[2 * tones.Length];
            int totalDuration = 0;

            for (int i = 0; i < tones.Length; i++)
            {
                messages[i * 2].DeltaTicks     = 0;
                messages[i * 2].MidiMsg        = (uint)(0x7F0090 | (tones[i].MIDINote << 8)); // Note on
                messages[i * 2 + 1].DeltaTicks = (uint)(tones[i].Duration);
                messages[i * 2 + 1].MidiMsg    = (uint)(0x7F0080 | (tones[i].MIDINote << 8)); // Note off

                totalDuration += tones[i].Duration;
            }

            byte[] headerData = new byte[messages.Length * WAVEFORMAT_MIDI_MESSAGE.Length];
            for (int i = 0; i < messages.Length; i++)
            {
                Buffer.BlockCopy(messages[i].GetBytes(), 0, headerData, i * WAVEFORMAT_MIDI_MESSAGE.Length, WAVEFORMAT_MIDI_MESSAGE.Length);
            }
            WaveHeader header = new WaveHeader(headerData);

            result = WaveAudio.NativeMethods.waveOutPrepareHeader(hWaveOut, header.Pointer, header.HeaderLength);
            Audio.CheckWaveError(result);

            result = WaveAudio.NativeMethods.waveOutWrite(hWaveOut, header.Pointer, header.HeaderLength);
            Audio.CheckWaveError(result);

            if (!hEvent.WaitOne(totalDuration * 20, false))
            {
                Debugger.Break();
            }

            result = WaveAudio.NativeMethods.waveOutUnprepareHeader(hWaveOut, header.Pointer, header.HeaderLength);
            Audio.CheckWaveError(result);

            result = WaveAudio.NativeMethods.waveOutClose(hWaveOut);
            Audio.CheckWaveError(result);
        }
Beispiel #2
0
        /// <summary>
        /// Begins running a standard application message loop on the current thread, and makes the specified form visible.
        /// </summary>
        /// <param name="mainForm">Form on which main message loop runs</param>
        /// <param name="runAsSingletonApp">When <b>true</b>, if an existing instance of the app is already running, the current application instance will simply exit and the already running app will come to the fore</param>
        /// <param name="displayMainForm">When set to true, the main form will be automatically displayed, else the app will be responsible for showing the Form</param>
        public static void Run(Form mainForm, bool runAsSingletonApp, bool displayMainForm)
        {
            bool isNew = true;

            NamedMutex m = new NamedMutex(true, Application2.StartupPath, out isNew);

            if (runAsSingletonApp)
            {
                if (!isNew)
                {
                    // activate the existing instance
                    EventWaitHandle wh = new EventWaitHandle(false, EventResetMode.AutoReset, Application2.StartupPath);
                    wh.Set();
                    return;
                }
                else
                {
                    //create a thread to wait for any subsequent instances to signal
                    remoteActivateThread = new Thread(new System.Threading.ThreadStart(RemoteActivateThreadProc));
                    remoteActivateThread.IsBackground = true;
                    remoteActivateThread.Name         = "SDF Application2 UI thread";
                    remoteActivateThread.Start();

                    // create a filter to track the currently active form so if
                    // we get reactivated from another instance attempting to run
                    // we know what Form to put topmost
                    currentFormFilter = new CurrentFormMessageFilter();
                    AddMessageFilter(currentFormFilter);
                }
            } // if (runAsSingletonApp)

            mainForm.Closed      += new EventHandler(MainFormExit);
            Application2.mainForm = mainForm;
            RunMessageLoop(displayMainForm);
        }
Beispiel #3
0
        /// <summary>
        /// Initializes a new instance of the Timer class
        /// </summary>
        /// <param name="interval">The Interval for the Timer</param>
        /// <param name="resolution">The resolution for the Timer</param>
        public Timer2(int interval, int resolution)
        {
            if (!NativeMethods.NativeEntryPointExists("mmtimer.dll", "timeSetEvent"))
            {
                throw new PlatformNotSupportedException("This platform does not have the required Multimedia timer support");
            }

            if (interval <= 0)
            {
                throw new ArgumentOutOfRangeException("interval");
            }
            if (resolution < 0)
            {
                throw new ArgumentOutOfRangeException("resolution");
            }

            m_waitHandle    = new EventWaitHandle(false, EventResetMode.AutoReset);
            m_elapsedThread = new Thread(new System.Threading.ThreadStart(ElapsedThreadProc));
            m_elapsedThread.IsBackground = true;
            m_elapsedThread.Name         = "SDF Timer2";
            m_elapsedThread.Start();

            this.Resolution = resolution;
            this.Interval   = interval;
        }
Beispiel #4
0
        private static void RemoteActivateThreadProc()
        {
            EventWaitHandle wh = new EventWaitHandle(false, EventResetMode.AutoReset, Application2.StartupPath);

            while (true)
            {
                wh.WaitOne();

                currentFormFilter.ActivateCurrentForm();
            }
        }
Beispiel #5
0
        /// <summary>
        /// Initializes a new instance of the FeedWorker.
        /// </summary>
        /// <param name="receiveCallback">A ReceiveHandler callback.</param>
        /// <param name="checkInterval">An interval (milliseconds) to start receiving RSS feeds.</param>
        public FeedWorker(ReceiveHandler receiveCallback, int checkInterval)
        {
            this.receiveCallback     = receiveCallback;
            FeedWorker.checkInterval = checkInterval;
            this.stop = false;
//#if !CF
//				resetEvent = new AutoResetEvent(false);
//#else
            resetEvent = new EventWaitHandle(false, EventResetMode.ManualReset);

//#endif
            feedList = new ArrayList();
            timer    = new Timer(new TimerCallback(TimerCall), resetEvent, Timeout.Infinite, Timeout.Infinite);
        }
Beispiel #6
0
            public void StopListen()
            {
                bool            createdNew = false;
                EventWaitHandle ewh        = new EventWaitHandle(false, EventResetMode.ManualReset, WaitHandleName, out createdNew);

                if (ewh != null)
                {
                    m_quit = true;
                    ewh.Set();
                    EventWaitHandle quit = new EventWaitHandle(false, EventResetMode.ManualReset, WaitHandleNameQuit, out createdNew);
                    quit.WaitOne(5000, true);
                }

                m_listening = false;
            }
Beispiel #7
0
 protected void Dispose(bool finalizing)
 {
     // Check to see if Dispose has already been called.
     if (!this.disposed)
     {
         // kill the worker thread
         m_quit = true;
         EventWaitHandle ewh = new EventWaitHandle(false, EventResetMode.ManualReset, WaitHandleName);
         ewh.Set();
     }
     if (!finalizing)
     {
         GC.SuppressFinalize(this);
     }
     disposed = true;
 }
Beispiel #8
0
        /// <summary>
        /// When overridden in a derived class, releases the unmanaged resources used by the LargeIntervalTimer, and optionally releases the managed resources.
        /// </summary>
        public void Dispose()
        {
            lock (m_interlock)
            {
                m_disposing = true;

                if (Enabled)
                {
                    Enabled = false;
                }

                if (m_quitHandle != null)
                {
                    m_quitHandle.Set();
                    m_quitHandle.Close();
                    m_quitHandle = null;
                }
            }
        }
Beispiel #9
0
        private void InternalThreadProc(object state)
        {
            ThreadCount++;

            int             source;
            string          eventName  = Guid.NewGuid().ToString();
            EventWaitHandle waitHandle = new EventWaitHandle(false, EventResetMode.AutoReset, eventName);

            if (TestCondition == 0)
            {
                Thread.Sleep(1000);
            }

            try
            {
                while (m_enabled)
                {
                    if (TestCondition == 1)
                    {
                        Thread.Sleep(1000);
                    }

                    if (m_disposing)
                    {
                        return;
                    }

                    if (TestCondition == 2)
                    {
                        Thread.Sleep(1000);
                    }

                    if (m_useFirstTime)
                    {
                        Notify.RunAppAtTime(string.Format(@"\\.\Notifications\NamedEvents\{0}", eventName), m_firstTime);
                        m_useFirstTime = false;
                    }
                    else
                    {
                        // set up the next event
                        Notify.RunAppAtTime(string.Format(@"\\.\Notifications\NamedEvents\{0}", eventName), DateTime.Now.Add(m_interval));
                        m_firstTime = DateTime.MinValue;
                    }

                    if (TestCondition == 3)
                    {
                        Thread.Sleep(1000);
                    }

                    if (m_disposing)
                    {
                        return;
                    }
                    source = OpenNETCF.Threading.EventWaitHandle.WaitAny(new WaitHandle[] { waitHandle, m_quitHandle });

                    if (TestCondition == 4)
                    {
                        Thread.Sleep(1000);
                    }

                    // see if it's the event
                    if (source == 0)
                    {
                        m_cachedEnabled = null;

                        // fire the event if we have a listener
                        if (Tick != null)
                        {
                            // we need to decouple this call from the current thread or the lock will do nothing
                            ThreadPool.QueueUserWorkItem(new WaitCallback(
                                                             delegate
                            {
                                Tick(this, null);
                            }));
                        }

                        if (TestCondition == 5)
                        {
                            Thread.Sleep(1000);
                        }

                        if (OneShot)
                        {
                            if (TestCondition == 6)
                            {
                                Thread.Sleep(1000);
                            }

                            if (m_cachedEnabled != null)
                            {
                                if (TestCondition == 7)
                                {
                                    Thread.Sleep(1000);
                                }
                                m_enabled = (m_cachedEnabled == true);
                                if (TestCondition == 8)
                                {
                                    Thread.Sleep(1000);
                                }
                            }
                            else
                            {
                                m_enabled = false;
                            }
                        }
                    }
                    else
                    {
                        m_enabled = false;
                    }
                }
            }
            finally
            {
                waitHandle.Close();
                ThreadCount--;
                if (ThreadCount == 0)
                {
                    m_quitHandle.Reset();
                }
            }
        }
Beispiel #10
0
 /// <summary>
 /// Creates an instance of a LargeIntervalTimer with a default interval of 60 seconds
 /// </summary>
 public LargeIntervalTimer()
 {
     m_quitHandle = new EventWaitHandle(false, EventResetMode.ManualReset);
 }
Beispiel #11
0
        private static void NotificationListenerProc()
        {
            int eventIndex = 0;

            while (!m_killThread)
            {
                // have to have a timeout or this thread never dies, even when the calling app is stopped
                eventIndex = EventWaitHandle.WaitAny(DeviceManagementInternals.m_events, 1000, true);

                switch (eventIndex)
                {
                case TIME_CHANGE_INDEX:
                    m_currentEvent = TimeChanged;
                    break;

                case TIMEZONE_CHANGE_INDEX:
                    m_currentEvent = TimeZoneChanged;
                    break;

                case PCCARD_CHANGE_INDEX:
                    m_currentEvent = PCCardChanged;
                    break;

                case IR_DISCOVERED_INDEX:
                    m_currentEvent = IRDiscovered;
                    break;

                case NET_CONNECT_INDEX:
                    m_currentEvent = NetworkConnected;
                    break;

                case NET_DISCONNECT_INDEX:
                    m_currentEvent = NetworkDisconnected;
                    break;

                case AC_APPLIED_INDEX:
                    m_currentEvent = ACPowerApplied;
                    break;

                case AC_REMOVED_INDEX:
                    m_currentEvent = ACPowerRemoved;
                    break;

                case RESTORE_INDEX:
                    m_currentEvent = DeviceRestoreComplete;
                    break;

                case SERIAL_DETECT_INDEX:
                    m_currentEvent = SerialDeviceDetected;
                    break;

                case SYNC_COMPLETE_INDEX:
                    m_currentEvent = SynchronizationComplete;
                    break;

                case WAKE_INDEX:
                    m_currentEvent = DeviceWake;
                    break;

                case NAME_CHANGE_INDEX:
                    m_currentEvent = DeviceNameChange;
                    break;

                case RNDIS_INDEX:
                    m_currentEvent = RNDISDeviceDetected;
                    break;

                case PROXY_CHANGE_INDEX:
                    m_currentEvent = InternetProxyChange;
                    break;

                default:
                    // most likely a timeout
                    m_currentEvent = null;
                    break;
                }

                if (m_currentEvent != null)
                {
                    try
                    {
                        m_invoker.Invoke(new EventHandler(NotificationMarshaler));
                    }
                    catch (Exception)
                    {
                        // failure here is catastropic, so just exit the thread
                        return;
                    }
                }
            }
        }
Beispiel #12
0
            internal DeviceManagementInternals()
            {
                // create all the notitification listener events
                m_events[TIME_CHANGE_INDEX] = new EventWaitHandle(
                    false, EventResetMode.AutoReset, TIME_CHANGE_EVENT);

                m_events[TIMEZONE_CHANGE_INDEX] = new EventWaitHandle(
                    false, EventResetMode.AutoReset, TIMEZONE_CHANGE_EVENT);

                m_events[PCCARD_CHANGE_INDEX] = new EventWaitHandle(
                    false, EventResetMode.AutoReset, PCCARD_CHANGE_EVENT);

                m_events[IR_DISCOVERED_INDEX] = new EventWaitHandle(
                    false, EventResetMode.AutoReset, IR_DISCOVERED_EVENT);

                m_events[NET_CONNECT_INDEX] = new EventWaitHandle(
                    false, EventResetMode.AutoReset, NET_CONNECT_EVENT);

                m_events[NET_DISCONNECT_INDEX] = new EventWaitHandle(
                    false, EventResetMode.AutoReset, NET_DISCONNECT_EVENT);

                m_events[AC_APPLIED_INDEX] = new EventWaitHandle(
                    false, EventResetMode.AutoReset, AC_APPLIED_EVENT);

                m_events[AC_REMOVED_INDEX] = new EventWaitHandle(
                    false, EventResetMode.AutoReset, AC_REMOVED_EVENT);

                m_events[RESTORE_INDEX] = new EventWaitHandle(
                    false, EventResetMode.AutoReset, RESTORE_EVENT);

                m_events[SERIAL_DETECT_INDEX] = new EventWaitHandle(
                    false, EventResetMode.AutoReset, SERIAL_DETECT_EVENT);

                m_events[SYNC_COMPLETE_INDEX] = new EventWaitHandle(
                    false, EventResetMode.AutoReset, SYNC_COMPLETE_EVENT);

                m_events[WAKE_INDEX] = new EventWaitHandle(
                    false, EventResetMode.AutoReset, WAKE_EVENT);

                m_events[NAME_CHANGE_INDEX] = new EventWaitHandle(
                    false, EventResetMode.AutoReset, NAME_CHANGE_EVENT);

                m_events[RNDIS_INDEX] = new EventWaitHandle(
                    false, EventResetMode.AutoReset, RNDIS_EVENT);

                m_events[PROXY_CHANGE_INDEX] = new EventWaitHandle(
                    false, EventResetMode.AutoReset, PROXY_CHANGE_EVENT);

                // set up all of the CeRunAppAtEvent notifications
                NativeMethods.CeRunAppAtEvent(NOTIFICATION_EVENT_PREFIX + TIME_CHANGE_EVENT, NotificationEvent.TimeChange);
                NativeMethods.CeRunAppAtEvent(NOTIFICATION_EVENT_PREFIX + TIMEZONE_CHANGE_EVENT, NotificationEvent.TimeZoneChange);
                NativeMethods.CeRunAppAtEvent(NOTIFICATION_EVENT_PREFIX + PCCARD_CHANGE_EVENT, NotificationEvent.DeviceChange);
                NativeMethods.CeRunAppAtEvent(NOTIFICATION_EVENT_PREFIX + IR_DISCOVERED_EVENT, NotificationEvent.IRDiscovered);
                NativeMethods.CeRunAppAtEvent(NOTIFICATION_EVENT_PREFIX + NET_CONNECT_EVENT, NotificationEvent.NetConnect);
                NativeMethods.CeRunAppAtEvent(NOTIFICATION_EVENT_PREFIX + NET_DISCONNECT_EVENT, NotificationEvent.NetDisconnect);
                NativeMethods.CeRunAppAtEvent(NOTIFICATION_EVENT_PREFIX + AC_APPLIED_EVENT, NotificationEvent.OnACPower);
                NativeMethods.CeRunAppAtEvent(NOTIFICATION_EVENT_PREFIX + AC_REMOVED_EVENT, NotificationEvent.OffACPower);
                NativeMethods.CeRunAppAtEvent(NOTIFICATION_EVENT_PREFIX + RESTORE_EVENT, NotificationEvent.RestoreEnd);
                NativeMethods.CeRunAppAtEvent(NOTIFICATION_EVENT_PREFIX + SERIAL_DETECT_EVENT, NotificationEvent.RS232Detected);
                NativeMethods.CeRunAppAtEvent(NOTIFICATION_EVENT_PREFIX + SYNC_COMPLETE_EVENT, NotificationEvent.SyncEnd);
                NativeMethods.CeRunAppAtEvent(NOTIFICATION_EVENT_PREFIX + WAKE_EVENT, NotificationEvent.Wakeup);
                NativeMethods.CeRunAppAtEvent(NOTIFICATION_EVENT_PREFIX + NAME_CHANGE_EVENT, NotificationEvent.MachineNameChange);
                NativeMethods.CeRunAppAtEvent(NOTIFICATION_EVENT_PREFIX + RNDIS_EVENT, NotificationEvent.RndisFNDetected);
                NativeMethods.CeRunAppAtEvent(NOTIFICATION_EVENT_PREFIX + PROXY_CHANGE_EVENT, NotificationEvent.InternetProxyChange);

                m_invoker.Disposed += new EventHandler(m_invoker_Disposed);
            }
Beispiel #13
0
            private unsafe void ThreadProc()
            {
                IntPtr notifyHandle = NativeMethods.FindFirstChangeNotification(m_path, true, filter);
                FileNotifyInformation notifyData = new FileNotifyInformation();
                uint returned  = 0;
                uint available = 0;

                EventWaitHandle ewh            = new EventWaitHandle(false, EventResetMode.ManualReset, WaitHandleName);
                EventWaitHandle quitWaitHandle = new EventWaitHandle(false, EventResetMode.ManualReset, WaitHandleNameQuit);

                while (!m_quit)
                {
                    ewh.Reset();

                    if (EventWaitHandle.WaitAny(new IntPtr[] { notifyHandle, ewh.Handle }, TimeoutInfinite, false) != EventWaitHandle.WaitTimeout)
                    {
                        if (m_quit)
                        {
                            break;
                        }

                        IntPtr ptr = IntPtr.Zero;
                        if (NativeMethods.CeGetFileNotificationInfo(notifyHandle, 0, ref ptr, 0, ref returned, ref available))
                        {
                            if (available > 0)
                            {
                                int maxData = 2048;
                                fixed(byte *pData = new byte[maxData])
                                {
                                    // get data
                                    if (NativeMethods.CeGetFileNotificationInfo(notifyHandle, 0, pData, maxData, ref returned, ref available))
                                    {
                                        notifyData = new FileNotifyInformation(pData, 0);

                                        // handle data in notifyData
                                        if (ValidateByFilter(notifyData.Filename))
                                        {
                                            RaiseEvents(notifyData.Action, notifyData.Filename);
                                        }

                                        int offset = 0;
                                        offset += notifyData.NextEntryOffset;

                                        while (notifyData.NextEntryOffset > 0)
                                        {
                                            notifyData = new FileNotifyInformation(pData, offset);

                                            if (ValidateByFilter(notifyData.Filename))
                                            {
                                                RaiseEvents(notifyData.Action, notifyData.Filename);
                                            }
                                            offset += notifyData.NextEntryOffset;
                                        }
                                    }
                                }
                            }
                            else
                            {
                                //Seems that subdirectories don't return anything but then the notifyHandle is never reset and if available data is 0 notifyHandle never resets
                                NativeMethods.FindCloseChangeNotification(notifyHandle);
                                notifyHandle = NativeMethods.FindFirstChangeNotification(m_path, true, filter);
                            }
                        }
                    } // if( waithandle...
                }     // while (!m_quit)

                NativeMethods.FindCloseChangeNotification(notifyHandle);
                quitWaitHandle.Set();
            }