Click here to Skip to main content
15,893,904 members
Articles / Mobile Apps / Windows Mobile

Start/Stop Your Music Player with your Headphones

Rate me:
Please Sign up or sign in to vote.
3.40/5 (7 votes)
8 Apr 2010CPOL2 min read 24.6K   394   15  
An application that starts your music app when you plug in the headphones and stops it when you unplug it!
using System;
using System.Windows.Forms;
using Microsoft.WindowsMobile.Status;
using System.Diagnostics;
using OpenNETCF.ToolHelp;
using System.Threading;
using System.Runtime.InteropServices;
using System.Reflection;



namespace AutoNitro
{
  static class Program
  {
    static SystemState bHPState;

    // Music application name and path. Change here if your music application is different
    const string MUSIC_APP_EXE_NAME = "Nitrogen.exe";
    const string MUSIC_APP_PROGRAM_FOLDER = "\\Program Files\\Nitrogen";

    public const Int32 NATIVE_ERROR_ALREADY_EXISTS = 183;

    // .NetCF does not export CreateMutex. We have to explicitly import it here
    [DllImport("coredll.dll", EntryPoint = "CreateMutex", SetLastError = true)]
    public static extern IntPtr CreateMutex(IntPtr lpMutexAttributes, bool InitialOwner, string MutexName);


    /*****************************************************************************************/
    /*****************************************************************************************/
    /*****************************************************************************************/
    [MTAThread]
    static void Main()
    {
      // The name of this application
      String sThisApp = Assembly.GetExecutingAssembly().GetName().Name + ".exe";

      // Check if an instance is already running by trying to create a mutex with a fixed name.
      // If mutex already exists, we assume that this is because another instance is running!
      IntPtr hMutex = CreateMutex(IntPtr.Zero, true, "AutoNitro");
      if (Marshal.GetLastWin32Error() == NATIVE_ERROR_ALREADY_EXISTS)
      {
        if (DialogResult.Yes == MessageBox.Show(sThisApp + " is already running. Do you want to close it?", 
                                                sThisApp, 
                                                MessageBoxButtons.YesNo, 
                                                MessageBoxIcon.Question, 
                                                MessageBoxDefaultButton.Button1))
        {
          // Kill 'em All!  
          ProcessEntry[] processes = OpenNETCF.ToolHelp.ProcessEntry.GetProcesses();
          foreach (OpenNETCF.ToolHelp.ProcessEntry process in processes)
          {
            if (String.Compare(process.ExeFile, sThisApp, StringComparison.InvariantCultureIgnoreCase) == 0)
            {
              process.Kill();
            }
          }
        }
        return;
      }

      // Register to be notified for any change to the HeadsetPreset property
      bHPState = new SystemState(SystemProperty.HeadsetPresent);
      bHPState.Changed += bState_Changed;
      
      // Probably better to implement a message loop here instead of sleeping and DoEvents
      while (true)
      {
        Application.DoEvents();
        Thread.Sleep(1000);
      }
    }

    /*****************************************************************************************/
    /*****************************************************************************************/
    /*****************************************************************************************/
    // Returns true if the application with the name passed as parameter is currently running
    static bool IsApplicationRunning(string pAppName)
    {
      ProcessEntry[] processes = OpenNETCF.ToolHelp.ProcessEntry.GetProcesses();
      foreach (OpenNETCF.ToolHelp.ProcessEntry process in processes)
      {
        if (String.Compare(process.ExeFile, pAppName, StringComparison.InvariantCultureIgnoreCase) == 0)
        {
          return true;
        }
      }
      return false;
    }

    /*****************************************************************************************/
    /*****************************************************************************************/
    /*****************************************************************************************/
    // Shutsdown all running instances of the application pAppName
    static void TerminateApplication(string pAppName)
    {
      ProcessEntry[] processes = OpenNETCF.ToolHelp.ProcessEntry.GetProcesses();
      foreach (OpenNETCF.ToolHelp.ProcessEntry process in processes)
      {
        if (String.Compare(process.ExeFile, pAppName, StringComparison.InvariantCultureIgnoreCase) == 0)
        {
          // We can directly kill the process here but it is not supposedly safe.
          // I don't prefer killing because the music app will not remember your last played
          // track and position if you kill it. Instead ask for a shutdown politely.
          Process p = System.Diagnostics.Process.GetProcessById((int)process.ProcessID);
          p.CloseMainWindow();
        }
      }
    }

    /*****************************************************************************************/
    /*****************************************************************************************/
    /*****************************************************************************************/
    private static void LaunchApplication(string pAppName)
    {
      System.Diagnostics.Process.Start(pAppName, "");
    }

    /*****************************************************************************************/
    /*****************************************************************************************/
    /*****************************************************************************************/
    static void bState_Changed(object sender, ChangeEventArgs args)
    {
      Boolean blNewHPState = Convert.ToBoolean(args.NewValue);
      bool blAppRunState = IsApplicationRunning(MUSIC_APP_EXE_NAME);

      if (!blNewHPState)
      {
        if (true == blAppRunState)
        {
          TerminateApplication(MUSIC_APP_EXE_NAME);
        }
      }
      else
      {
        if (false == blAppRunState)
        {
          string sApp = MUSIC_APP_PROGRAM_FOLDER + "\\" + MUSIC_APP_EXE_NAME;
          try
          {
            LaunchApplication(sApp);
          }
          catch
          {
            throw new Exception("Failed to start music player.\nPath was " + sApp);
          }
        }
      }
    }
  }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions