private bool HookSpotify()
        {
            children = new HashSet <int>();

            // Try hooking through window title
            foreach (Process p in Process.GetProcessesByName("spotify"))
            {
                children.Add(p.Id);
                Spotify = p;
                if (p.MainWindowTitle.Length > 1)
                {
                    return(true);
                }
            }

            // Try hooking through audio device
            volumeControl = AudioUtils.GetVolumeControl(children);
            if (volumeControl != null)
            {
                Spotify = Process.GetProcessById(volumeControl.ProcessId);
                return(true);
            }

            return(false);
        }
 public void CleanHook()
 {
     Spotify = null;
     handle  = IntPtr.Zero;
     if (volumeControl != null)
     {
         Marshal.ReleaseComObject(volumeControl.Control);
     }
     volumeControl = null;
     Hooked        = false;
 }
        public SpotifyState Check()
        {
            if (!Hooked) //if never or no more hooked, start hook
            {
                Hooked = HookSpotify();
            }
            else if (!IsRunning()) // if hooked and spotify no more running, clean hook
            {
                CleanHook();
            }
            else // else inspect spotify process
            {
                if (volumeControl != null)
                {
                    lastPeak = peak;
                    peak     = AudioUtils.GetPeakVolume(volumeControl.Control);
                }
                else
                {
                    volumeControl = AudioUtils.GetVolumeControl(children);
                }

                if (Spotify.HasExited)
                {
                    handle = IntPtr.Zero;
                    return(SpotifyState.NonHooked);
                }

                handle = Spotify.MainWindowHandle;
                var windowName = Spotify.MainWindowTitle;

                if (windowName.Equals("Spotify Free"))
                {
                    return(SpotifyState.Pause);
                }
                if ((windowName.Equals("Advertisement") || windowName.Equals("Spotify")) && IsPlaying())
                {
                    return(SpotifyState.PlayingAd);
                }
                if (IsPlaying())
                {
                    return(SpotifyState.Playing);
                }
            }

            return(SpotifyState.NonHooked);
        }