예제 #1
1
        public FormSwitcher()
        {
            InitializeComponent();

            var winVer = FileVersionInfo.GetVersionInfo(Environment.GetEnvironmentVariable("windir") + "\\explorer.exe");
            IsWin10 = winVer.ProductMajorPart == 10;
            if (IsWin10)
                FormBorderStyle = FormBorderStyle.FixedToolWindow;
            SetWindowTheme(listDevices.Handle, "explorer", null);

            ledLeft.OldStyle = Program.settings.ColorVU;
            ledLeft.SetValue((float)0.1);
            ledRight.OldStyle = Program.settings.ColorVU;
            ledRight.SetValue((float)0.1);

            using (var gr = CreateGraphics())
                DpiFactor = gr.DpiX / 96;
            var tile = new Size(listDevices.ClientSize.Width + 2, (int)(listDevices.TileSize.Height * DpiFactor));

            DeviceIcons.InitImageLists(DpiFactor);

            listDevices.TileSize = tile;
            listDevices.Scroll += VolBar.DoScroll;
            ledLeft.DoScroll += VolBar.DoScroll;
            ledRight.DoScroll += VolBar.DoScroll;
            listDevices.LargeImageList = DeviceIcons.ActiveIcons;

            if (DpiFactor <= 1)
            {
                DefaultTrayIcons.Add(getIcon(Resources.mute));
                DefaultTrayIcons.Add(getIcon(Resources.zero));
                DefaultTrayIcons.Add(getIcon(Resources._1_33));
                DefaultTrayIcons.Add(getIcon(Resources._33_66));
                DefaultTrayIcons.Add(getIcon(Resources._66_100));
            }
            else
            {
                DefaultTrayIcons.Add(getIcon(Resources.mute_highDPI));
                DefaultTrayIcons.Add(getIcon(Resources.zero_highDPI));
                DefaultTrayIcons.Add(getIcon(Resources._1_33_highDPI));
                DefaultTrayIcons.Add(getIcon(Resources._33_66_highDPI));
                DefaultTrayIcons.Add(getIcon(Resources._66_100_highDPI));
            }

            RenderType = Program.settings.DefaultDataFlow;
            RefreshDevices(RenderType);
            SetTrayIcons();

            VolBar.VolumeMuteChanged += IconChanged;
            VolBar.RegisterDevice(RenderType);
            EndPoints.NotifyClient.DefaultChanged += DefaultChanged;
            EndPoints.NotifyClient.DeviceAdded += DeviceAdded;
            EndPoints.NotifyClient.DeviceRemoved += DeviceRemoved;

            GlobalHotkeys.Handle = Handle;
            GlobalHotkeys.RegisterAll();

            ScrollVolume.VolumeScroll += ScrollTheVolume;
            ScrollVolume.RegisterVolScroll(Program.settings.VolumeScroll.Enabled);
        }
 public MMDeviceCollection EnumerateAudioEndPoints(EDataFlow dataFlow, EDeviceState dwStateMask)
 {
     IMMDeviceCollection result;
     //Marshal.ThrowExceptionForHR(_realEnumerator.EnumAudioEndpoints(dataFlow, dwStateMask, out result));
     _realEnumerator.EnumAudioEndpoints(dataFlow, dwStateMask, out result);
     return new MMDeviceCollection(result, dataFlow, dwStateMask);
 }
예제 #3
0
        public MMDevice GetDefaultAudioEndpoint(EDataFlow dataFlow, ERole role)
        {
            IMMDevice result;

            Marshal.ThrowExceptionForHR(_deviceEnumerator.GetDefaultAudioEndpoint(dataFlow, role, out result));
            return(new MMDevice(result));
        }
        public MorphicResult <MMDevice, WindowsComError> GetDefaultAudioEndpoint(EDataFlow dataFlow, ERole role)
        {
            IMMDevice?immDevice;
            var       result = _mmDeviceEnumerator.GetDefaultAudioEndpoint(dataFlow, role, out immDevice);

            if (result != ExtendedPInvoke.S_OK)
            {
                if (result == ExtendedPInvoke.E_NOTFOUND)
                {
                    throw new NoDeviceIsAvailableException();
                }
                else
                {
                    // TODO: consider throwing more granular exceptions here
                    var comException = new COMException("IMMDeviceEnumerator.GetDefaultAudioEndpoint failed", Marshal.GetExceptionForHR(result));
                    return(MorphicResult.ErrorResult(WindowsComError.ComException(comException)));
                }
            }

            if (immDevice is null)
            {
                // NOTE: this code should never be executed since GetDefaultAudioEndpoint should have returned an HRESULT of E_POINTER if it failed
                var comException = new COMException("IMMDeviceEnumerator.GetDefaultAudioEndpoint returned a null pointer", new NullReferenceException());
                return(MorphicResult.ErrorResult(WindowsComError.ComException(comException)));
            }

            var mmDevice = MMDevice.CreateFromIMMDevice(immDevice !);

            return(MorphicResult.OkResult(mmDevice));
        }
 public MMDevice GetDefaultAudioEndpoint(EDataFlow dataFlow, ERole role)
 {
     IMMDevice _Device = null;
     //Marshal.ThrowExceptionForHR(((IMMDeviceEnumerator)_realEnumerator).GetDefaultAudioEndpoint(dataFlow, role, out _Device));
     _realEnumerator.GetDefaultAudioEndpoint(dataFlow, role, out _Device);
     return new MMDevice(_Device);
 }
예제 #6
0
        public bool IsDefault(string deviceId, EDataFlow flow, Role role)
        {
            if (string.IsNullOrWhiteSpace(deviceId))
            {
                return(false);
            }

            if (role == Role.All)
            {
                var result = true;
                result &= IsDefault(deviceId, flow, Role.Communications);
                result &= IsDefault(deviceId, flow, Role.Console);
                result &= IsDefault(deviceId, flow, Role.Multimedia);

                return(result);
            }

            try
            {
                MMDevice defaultDevice = _enumerator.GetDefaultAudioEndpoint((EDataFlow)flow, (Role)role);
                return(deviceId == defaultDevice.ID);
            }
            catch (Exception)
            {
                //Happens if there is no default device for the given Data Flow and/or role
                // See issue #401
                return(false);
            }
        }
예제 #7
0
        public MMDevice GetDefaultAudioEndpoint(EDataFlow dataFlow, ERole role)
        {
            IMMDevice?immDevice;
            var       result = _mmDeviceEnumerator.GetDefaultAudioEndpoint(dataFlow, role, out immDevice);

            if (result != WindowsApi.S_OK)
            {
                if (result == WindowsApi.E_NOTFOUND)
                {
                    throw new NoDeviceIsAvailableException();
                }
                else
                {
                    // TODO: consider throwing more granular exceptions here
                    throw new COMException("IMMDeviceEnumerator.GetDefaultAudioEndpoint failed", Marshal.GetExceptionForHR(result));
                }
            }

            if (immDevice == null)
            {
                // NOTE: this code should never be executed since GetDefaultAudioEndpoint should have returned an HRESULT of E_POINTER if it failed
                throw new COMException("IMMDeviceEnumerator.GetDefaultAudioEndpoint returned a null pointer", new NullReferenceException());
            }

            var mmDevice = MMDevice.CreateFromIMMDevice(immDevice !);

            return(mmDevice);
        }
예제 #8
0
 public DeviceInfo(string deviceId, string name, EDataFlow flow, EDeviceState state)
 {
     _deviceId     = deviceId;
     _friendlyName = name;
     _dataFlow     = flow;
     _state        = state;
 }
예제 #9
0
            /*/
             * /// <summary>
             * /// IMMNotificationClient : OnDeviceStateChanged
             * /// </summary>
             * /// <param name="deviceId"></param>
             * /// <param name="newState"></param>
             * public void OnDeviceStateChanged(
             *          [MarshalAs(UnmanagedType.LPWStr)] string deviceId,
             *          [MarshalAs(UnmanagedType.U4)] EDeviceState newState)
             * {
             *  // Console.WriteLine("OnDeviceStateChanged: deviceId="+ deviceId +", state=" + newState);
             *
             *  if (newState == EDeviceState.Active)
             *  {
             *      //Console.WriteLine("Active");
             *  }
             *  else if (newState == EDeviceState.NotPresent)
             *  {
             *      // Console.WriteLine("NotPresent");
             *  }
             *  //releaseDevice();
             *  //initDevice();
             * }
             *
             * /// <summary>
             * /// IMMNotificationClient : OnDeviceAdded
             * /// </summary>
             * /// <param name="deviceId"></param>
             * public void OnDeviceAdded([MarshalAs(UnmanagedType.LPWStr)] string deviceId)
             * {
             *  //Console.WriteLine("OnDeviceAdded:" + deviceId);
             * }
             *
             * /// <summary>
             * /// IMMNotificationClient : OnDeviceRemoved
             * /// </summary>
             * /// <param name="deviceId"></param>
             * public void OnDeviceRemoved(
             *  [MarshalAs(UnmanagedType.LPWStr)] string deviceId)
             * {
             *  //Console.WriteLine("OnDeviceRemoved:" + deviceId);
             * }
             * /// <summary>
             * /// IMMNotificationClient : OnPropertyValueChanged
             * /// </summary>
             * /// <param name="deviceId"></param>
             * /// <param name="propertyKey"></param>
             * public void OnPropertyValueChanged(
             *  [MarshalAs(UnmanagedType.LPWStr)] string deviceId, PropertyKey propertyKey)
             * {
             *  //Console.WriteLine("OnPropertyValueChanged:" + deviceId);
             * }
             * //*/

            /// <summary>
            /// IMMNotificationClient : OnDefaultDeviceChanged
            /// </summary>
            /// <param name="dataFlow"></param>
            /// <param name="deviceRole"></param>
            /// <param name="defaultDeviceId"></param>
            public void OnDefaultDeviceChanged(
                [MarshalAs(UnmanagedType.I4)] EDataFlow dataFlow,
                [MarshalAs(UnmanagedType.I4)] ERole deviceRole,
                [MarshalAs(UnmanagedType.LPWStr)] string defaultDeviceId)
            {
                //Console.WriteLine("OnDefaultDeviceChanged:  DeviceId:[" + defaultDeviceId + "] EDataFlow:[" + dataFlow+ "] ERole:[" + deviceRole+"]");
                if (dataFlow != monitor.DataFlow || deviceRole != monitor.Role)
                {
                    return;
                }


                var dispatcher = Application.Current.Dispatcher;

                //dispatcher.Invoke(DispatcherPriority.Normal, (Action)delegate () {
                dispatcher.Invoke((Action) delegate()
                {
                    monitor.updateDevice(defaultDeviceId);

                    // if (monitor.listener == null)
                    // {
                    //    return;
                    //}
                    //
                    //monitor.listener.OnDeviceChanged(monitor.device);

                    Debug.WriteLine($"OnDefaultDeviceChanged flow={dataFlow} role={deviceRole} device={defaultDeviceId} list={(_OnAudioDeviceChanged?.GetInvocationList().Length ?? 0)}");
                    _OnAudioDeviceChanged?.Invoke(monitor.device);
                });
            }
예제 #10
0
        public MMDeviceCollection EnumerateAudioEndPoints(EDataFlow dataFlow, EDeviceState dwStateMask)
        {
            IMMDeviceCollection result;

            Marshal.ThrowExceptionForHR(_realEnumerator.EnumAudioEndpoints(dataFlow, dwStateMask, out result));
            return(new MMDeviceCollection(result));
        }
예제 #11
0
        public MMDevice GetDefaultAudioEndpoint(EDataFlow dataFlow, ERole role)
        {
            IMMDevice _Device;

            Marshal.ThrowExceptionForHR(_realEnumerator.GetDefaultAudioEndpoint(dataFlow, role, out _Device));
            return(new MMDevice(_Device));
        }
예제 #12
0
        private void notifyIcon1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if (Program.settings.QuickSwitchEnabled && !DeactivatedOnIcon)
                {
                    notifyIcon.ContextMenuStrip = null;
                    QuickSwitchDevice(false, Program.settings.DefaultDataFlow, Program.settings.QuickSwitchShowOSD);
                }
                else
                {
                    notifyIcon.ContextMenuStrip = trayMenu;
                }

                return;
            }

            var rType = Program.settings.DefaultDataFlow;

            if (ModifierKeys.HasFlag(Keys.Control))
            {
                rType = rType == EDataFlow.eRender ? EDataFlow.eCapture : EDataFlow.eRender;
            }

            RenderType = rType;
            RefreshDevices(RenderType);

            if (DeactivatedOnIcon)
            {
                return;
            }

            SetSizes();
        }
예제 #13
0
        /// <summary>
        /// Creates the specified collection of the IMMDevice interfaces.
        /// </summary>
        /// <param name="direction">The data flow direction.</param>
        /// <param name="stateMasks">The state masks.</param>
        public static IEnumerable <IMMDevice> CreateIMMDeviceCollection(EDataFlow direction, UInt32 stateMasks)
        {
            var deviceEnumerator = CreateIMMDeviceEnumerator();

            IMMDeviceCollection deviceCollection;

            deviceEnumerator.EnumAudioEndpoints(direction, stateMasks, out deviceCollection);

            UInt32 deviceCount;

            deviceCollection.GetCount(out deviceCount);

            var deviceList = new List <IMMDevice>();

            for (uint i = 0; i < deviceCount; i++)
            {
                IMMDevice device;
                deviceCollection.Item(i, out device);
                deviceList.Add(device);
            }

            if (!deviceList.Any())
            {
                Assert.Inconclusive("The test cannot be run properly. No devices were found.");
            }

            return(deviceList);
        }
예제 #14
0
        /// <summary>
        /// Switch the audio endpoint of the given process
        /// </summary>
        /// <param name="deviceId">Id of the device</param>
        /// <param name="role">Which role to switch</param>
        /// <param name="flow">Which flow to switch</param>
        /// <param name="processId">ProcessID of the process</param>
        public void SwitchProcessTo(string deviceId, ERole role, EDataFlow flow, uint processId)
        {
            var roles = new[]
            {
                ERole.eConsole,
                ERole.eCommunications,
                ERole.eMultimedia
            };

            if (role != ERole.ERole_enum_count)
            {
                roles = new[]
                {
                    role
                };
            }

            ComThread.Invoke((() =>
            {
                var currentEndpoint = roles.Select(eRole => ExtendPolicyClient.GetDefaultEndPoint(flow, eRole, processId)).FirstOrDefault(endpoint => !string.IsNullOrEmpty(endpoint));
                if (deviceId.Equals(currentEndpoint))
                {
                    Trace.WriteLine($"Default endpoint for {processId} already {deviceId}");
                    return;
                }

                ExtendPolicyClient.SetDefaultEndPoint(deviceId, flow, roles, processId);
            }));
        }
예제 #15
0
        /// <summary>
        /// Find audio endpoint by name
        /// </summary>
        /// <param name="name">the name of the endpint</param>
        /// <param name="deviceflow">whenever it is input or output or both</param>
        /// <param name="state">whenever it is enabled,disabled unpluged or both</param>
        /// <returns>the desired endpoint</returns>
        public MMDevice FindEndpointByName(string name, EDataFlow deviceflow,
                                           EDeviceState state)
        {
            try
            {
                MMDevice           device  = null;
                MMDeviceCollection devices = this.GetAllAudioEndPoints(deviceflow, state);

                if (devices != null)
                {
                    for (int i = 0; i < devices.Count; i++)
                    {
                        MMDevice deviceAt = devices[i];
                        if (deviceAt.FriendlyName.ToLower() == name)
                        {
                            device = deviceAt;
                            break;
                        }
                    }
                }



                return(device);
            }
            catch (Exception e)
            {
                Program.Bugtracking(e);
                return(null);
            }
        }
예제 #16
0
        public int OnDefaultDeviceChanged(EDataFlow flow, ERole role, string strDefaultDeviceId)
        {
            DefaultDeviceChangedEventArgs arg = new DefaultDeviceChangedEventArgs(flow, role, strDefaultDeviceId);

            _DeviceEnumerator.FireDefaultDeviceChangedEvent(arg);
            return(0);
        }
예제 #17
0
        private void notifyIcon1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                return;
            }

            var rType = Program.settings.DefaultDataFlow;

            if (ModifierKeys.HasFlag(Keys.Control))
            {
                rType = rType == EDataFlow.eRender ? EDataFlow.eCapture : EDataFlow.eRender;
            }

            if (ModifierKeys.HasFlag(Keys.Alt))
            {
                ChangeDeviceState(rType, true, 0, true);
            }
            else
            {
                RenderType = rType;
                RefreshDevices(RenderType);

                if (DeactivatedOnIcon)
                {
                    return;
                }

                SetSizes();
            }
        }
예제 #18
0
        void DeviceChanged(
            [MarshalAs(UnmanagedType.I4)] EDataFlow dataFlow,
            [MarshalAs(UnmanagedType.I4)] ERole deviceRole,
            [MarshalAs(UnmanagedType.LPWStr)] string defaultDeviceId)
        {
            if (deviceRole != this.Role)
            {
                return;
            }

            var dispatcher = Application.Current.Dispatcher;

            //dispatcher.Invoke(DispatcherPriority.Normal, (Action)delegate () {
            dispatcher.BeginInvoke((Action) delegate()
            {
                if (!Initialized)
                {
                    return;
                }

                Debug.WriteLine($"MicPlayter Stop(DeviceChanged) Role={deviceRole} Flow={dataFlow} ID={defaultDeviceId}");
                Stop();
                Dispose();
                //var newDevice = deviceEnumerator.GetDevice(defaultDeviceId);
            });
        }
예제 #19
0
        public MMDevice GetDefaultAudioEndpoint(EDataFlow dataFlow, ERole role)
        {
            IMMDevice ppEndpoint = null;

            Marshal.ThrowExceptionForHR(this._realEnumerator.GetDefaultAudioEndpoint(dataFlow, role, out ppEndpoint));
            return(new MMDevice(ppEndpoint));
        }
예제 #20
0
        internal void RegisterDevice(EDataFlow RenderType)
        {
            if (Device != null)
            {
                try
                {
                    Device.AudioEndpointVolume.OnVolumeNotification -= VolNotify;
                    if (volEvents != null)
                    {
                        Device.AudioSessionManager.Sessions[0].UnregisterAudioSessionNotification(volEvents);
                    }
                    volEvents = null;
                }
                catch { }
                Device = null;
            }

            Device    = EndPoints.DeviceEnumerator.GetDefaultAudioEndpoint(RenderType, ERole.eMultimedia);
            Value     = Device.AudioEndpointVolume.MasterVolumeLevelScalar;
            Mute      = Device.AudioEndpointVolume.Mute;
            Stereo    = Device.AudioMeterInformation.Channels.GetCount() > 1;
            volEvents = new VolEventsHandler(this);
            Device.AudioSessionManager.Sessions[0].RegisterAudioSessionNotification(volEvents);
            Device.AudioEndpointVolume.OnVolumeNotification += VolNotify;
        }
예제 #21
0
        internal static void RefreshDeviceList(EDataFlow renderType)
        {
            DeviceNames.Clear();
            DeviceIDs.Clear();

            var pDevices    = DeviceEnumerator.EnumerateAudioEndPoints(renderType, EDeviceState.Active);
            var defDeviceID = DeviceEnumerator.GetDefaultAudioEndpoint(renderType, ERole.eMultimedia).ID;
            var devCount    = pDevices.Count;
            var newCount    = 0;

            for (var i = 0; i < devCount; i++)
            {
                var device = pDevices[i];
                var devID  = device.ID;

                var devSettings = Program.settings.Device.Find(x => x.DeviceID == devID);
                if (devSettings == null || !devSettings.HideFromList)
                {
                    var devName = device.FriendlyName;
                    DeviceNames.Add(devID, devName);
                    DeviceIDs.Add(newCount, devID);

                    if (devID == defDeviceID)
                    {
                        DefaultDeviceID   = newCount;
                        DefaultDeviceName = devName;
                    }
                    newCount++;
                }
            }
        }
예제 #22
0
        /// <summary>
        /// Attempts to set active device to the specified name
        /// </summary>
        /// <param name="device"></param>
        public static bool SetActiveDevice(string deviceId, EDataFlow deviceType)
        {
            AudioSwitcher switch1 = AudioSwitcher.Instance;

            //Log.Information("Set Default device: {Device}", device);
            if (!IsSwitchDefaultDevice)
            {
                switch1.SwitchTo(deviceId, Role.Console);
                switch1.SwitchTo(deviceId, Role.Multimedia);
                if (SwitchForegroundProgram)
                {
                    switch1.ResetProcessDeviceConfiguration();
                    switch1.SwitchProcessTo(deviceId, Role.Console, deviceType);
                    switch1.SwitchProcessTo(deviceId, Role.Multimedia, deviceType);
                }
            }
            else
            {
                //Log.Information("Set Default Communication device: {Device}", device);
                switch1.SwitchTo(deviceId, Role.All);
                if (SwitchForegroundProgram)
                {
                    switch1.ResetProcessDeviceConfiguration();
                    switch1.SwitchProcessTo(deviceId, Role.All, deviceType);
                }
            }
            return(true);
        }
예제 #23
0
        public void SetDefaultEndPoint(string deviceId, EDataFlow flow, IEnumerable <ERole> roles, uint processId)
        {
            Trace.WriteLine($"ExtendedPolicyClient SetDefaultEndPoint {deviceId} [{flow}] {processId}");
            try
            {
                if (string.IsNullOrEmpty(deviceId))
                {
                    return;
                }

                using var deviceIdStr = HSTRING.FromString(GenerateDeviceId(deviceId, flow));
                foreach (var eRole in roles)
                {
                    PolicyConfig.SetPersistedDefaultAudioEndpoint(processId, flow, eRole, deviceIdStr);
                }
            }
            catch (COMException e) when((e.ErrorCode & ErrorConst.COM_ERROR_MASK) == ErrorConst.COM_ERROR_NOT_FOUND)
            {
                throw new DeviceNotFoundException($"Can't set default as {deviceId}", e, deviceId);
            }
            catch (Exception ex)
            {
                Trace.WriteLine($"{ex}");
            }
        }
예제 #24
0
 public void OnDefaultDeviceChanged(EDataFlow dataFlow, ERole deviceRole, string defaultDeviceId)
 {
     if (DefaultChanged != null)
     {
         DefaultChanged(defaultDeviceId);
     }
 }
예제 #25
0
        /// <summary>
        /// Enumerate Audio Endpoints
        /// </summary>
        /// <param name="dataFlow">Desired DataFlow</param>
        /// <param name="dwStateMask">State Mask</param>
        /// <returns>Device Collection</returns>
        public IReadOnlyCollection <DeviceFullInfo> EnumerateAudioEndPoints(EDataFlow dataFlow, DeviceState dwStateMask)
        {
            IMMDeviceCollection result;

            Marshal.ThrowExceptionForHR(_realEnumerator.EnumAudioEndpoints(dataFlow, dwStateMask, out result));
            return(CreateDeviceList(new MMDeviceCollection(result)));
        }
예제 #26
0
        internal static void RefreshDeviceList(EDataFlow renderType)
        {
            DeviceNames.Clear();
            DeviceIDs.Clear();

            var pDevices = DeviceEnumerator.EnumerateAudioEndPoints(renderType, EDeviceState.Active);
            var defDeviceID = DeviceEnumerator.GetDefaultAudioEndpoint(renderType, ERole.eMultimedia).ID;
            var devCount = pDevices.Count;
            var newCount = 0;

            for (var i = 0; i < devCount; i++)
            {
                var device = pDevices[i];
                var devID = device.ID;
                
                var devSettings = Program.settings.Device.Find(x => x.DeviceID == devID);
                if (devSettings == null || !devSettings.HideFromList)
                {
                    var devName = device.FriendlyName;
                    DeviceNames.Add(devID, devName);
                    DeviceIDs.Add(newCount, devID);
                    
                    if (devID == defDeviceID)
                    {
                        DefaultDeviceID = newCount;
                        DefaultDeviceName = devName;
                    }
                    newCount++;
                }
            }
        }
예제 #27
0
        internal static void RefreshDevices(EDataFlow renderType, bool updateIcons)
        {
            DeviceNames.Clear();
            DeviceIDs.Clear();

            if (updateIcons)
            {
                DeviceIcons.Clear();
            }

            var pDevices = pEnum.EnumerateAudioEndPoints(renderType, EDeviceState.DEVICE_STATE_ACTIVE);
            var devCount = pDevices.Count;

            for (var i = 0; i < devCount; i++)
            {
                var device = pDevices[i];
                DeviceNames.Add(device.FriendlyName);
                DeviceIDs.Add(i, device.ID);

                if (updateIcons)
                {
                    DeviceIcons.Add(device.IconPath);
                }
            }
        }
예제 #28
0
        public void PostConstructor(EDataFlow dataFlow)
        {
            var devices = EDataFlow.eRender.Equals(dataFlow) ? DeviceRepository.FindPlayBackDevices() : DeviceRepository.FindCaptureDevices();
            var cnt     = 0;

            foreach (var dev in devices)
            {
                var devID  = dev.MMDevice.ID;
                var lvitem = new ListViewItem {
                    Text = dev.MMDevice.FriendlyName, ImageIndex = cnt, Tag = devID
                };

                var devSettings = Program.settings.Device.Find(x => x.DeviceID == devID);
                if (devSettings != null)
                {
                    lvitem.Font = new Font(lvitem.Font, FontStyle.Bold);

                    if (devSettings.HideFromList)
                    {
                        lvitem.Font = new Font(lvitem.Font, FontStyle.Italic);
                    }
                }

                listDevices.LargeImageList.Images.Add(DeviceIcons.GetIcon(dev.MMDevice.IconPath));
                listDevices.Items.Add(lvitem);
                cnt++;
            }
        }
        public void SetDefaultEndPoint(string deviceId, EDataFlow flow, IEnumerable <ERole> roles, uint processId)
        {
            Trace.WriteLine($"ExtendedPolicyClient SetDefaultEndPoint {deviceId} [{flow}] {processId}");
            try
            {
                var stringPtrDeviceId = IntPtr.Zero;

                if (!string.IsNullOrWhiteSpace(deviceId))
                {
                    var str = GenerateDeviceId(deviceId, flow);
                    ComBase.WindowsCreateString(str, (uint)str.Length, out stringPtrDeviceId);
                }

                foreach (var eRole in roles)
                {
                    PolicyConfig.SetPersistedDefaultAudioEndpoint(processId, flow, eRole, stringPtrDeviceId);
                }
            }
            catch (COMException e) when((e.ErrorCode & ErrorConst.COM_ERROR_MASK) == ErrorConst.COM_ERROR_NOT_FOUND)
            {
                throw new DeviceNotFoundException($"Can't set default as {deviceId}", e, deviceId);
            }
            catch (Exception ex)
            {
                Trace.WriteLine($"{ex}");
            }
        }
예제 #30
0
 public void OnDefaultDeviceChanged(
     [MarshalAs(UnmanagedType.I4)] EDataFlow dataFlow,
     [MarshalAs(UnmanagedType.I4)] ERole deviceRole,
     [MarshalAs(UnmanagedType.LPWStr)] string defaultDeviceId)
 {
     parent.FireOnDefaultDeviceChanged(dataFlow, deviceRole, defaultDeviceId);
 }
예제 #31
0
 internal void FireOnDefaultDeviceChanged(
     [MarshalAs(UnmanagedType.I4)] EDataFlow dataFlow,
     [MarshalAs(UnmanagedType.I4)] ERole deviceRole,
     [MarshalAs(UnmanagedType.LPWStr)] string defaultDeviceId)
 {
     //Debug.WriteLine($"OnDefaultDeviceChanged flow={dataFlow} role={deviceRole} device={defaultDeviceId} list={(_OnDefaultDeviceChanged?.GetInvocationList().Length??0)}");
     _OnDefaultDeviceChanged?.Invoke(dataFlow, deviceRole, defaultDeviceId);
 }
예제 #32
0
 /// <summary>
 /// Get Default Endpoint
 /// </summary>
 /// <param name="dataFlow">Data Flow</param>
 /// <param name="role">Role</param>
 /// <returns>Device</returns>
 public MMDevice GetDefaultAudioEndpoint(EDataFlow dataFlow, Role role)
 {
     if (_enumerator.HasDefaultAudioEndpoint(dataFlow, role))
     {
         return(_enumerator.GetDefaultAudioEndpoint(dataFlow, role));
     }
     return(null);
 }
예제 #33
0
 internal void RegisterDevice(EDataFlow RenderType)
 {
     Device = EndPoints.DeviceEnumerator.GetDefaultAudioEndpoint(RenderType, ERole.eMultimedia);
     Value  = Device.AudioEndpointVolume.MasterVolumeLevelScalar;
     Mute   = Device.AudioEndpointVolume.Mute;
     Stereo = Device.AudioMeterInformation.Channels.GetCount() > 1;
     Device.AudioEndpointVolume.OnVolumeNotification += VolNotify;
 }
 /// <summary>
 /// Called when the default Endpoint device for a given role changes
 /// </summary>
 /// <param name="flow">The dataflow direction</param>
 /// <param name="role">The role</param>
 /// <param name="deviceId">The ID of the Endpoint device that is now the default for the specified role</param>
 public int OnDefaultDeviceChanged(EDataFlow flow, ERole role, string deviceId)
 {
     if (flow == EDataFlow.Render && role == ERole.Console)
     {
         this.DefaultDeviceChanged?.Invoke(deviceId);
     }
     return(0);
 }
예제 #35
0
 private void FormSwitcher_Deactivate(object sender, EventArgs e)
 {
     Hide();
     timer1.Enabled = false;
     VolBar.UnregisterDevice();
     RenderType = EDataFlow.eRender;
     RefreshDevices(false);
     VolBar.RegisterDevice(RenderType);
 }
예제 #36
0
        internal static string SetPrevDefault(EDataFlow rType)
        {
            RefreshDeviceList(rType);

            if (DefaultDeviceID == 0)
                DefaultDeviceID = DeviceNames.Count - 1;
            else
                DefaultDeviceID--;

            SetDefaultDeviceByID(DefaultDeviceID);
            return DeviceNames[DeviceIDs[DefaultDeviceID]];
        }
예제 #37
0
        internal static string SetNextDefault(EDataFlow rType)
        {
            RefreshDeviceList(rType);

            if (DefaultDeviceID == DeviceNames.Count - 1)
                DefaultDeviceID = 0;
            else
                DefaultDeviceID++;

            SetDefaultDeviceByID(DefaultDeviceID);
            return DeviceNames[DeviceIDs[DefaultDeviceID]];
        }
 public void OnDefaultDeviceChanged(EDataFlow flow, ERole role, string defaultDeviceId)
 {
     try
     {
         if (DefaultDeviceChanged != null)
         {
             DefaultDeviceChanged(flow, role, defaultDeviceId);
         }
     }
     catch (Exception ex)
     {
     }
 }
예제 #39
0
파일: Mute.cs 프로젝트: keoto/Arma3.Mute
        private static void FindApplication(string appName)
        {
            EDataFlow flow = new EDataFlow();
            MMDeviceEnumerator deviceEnum = new MMDeviceEnumerator();

            devCol = deviceEnum.EnumerateAudioEndPoints(flow, DEVICE_STATE.DEVICE_STATE_ACTIVE);

            for (int devIdx = 0; devIdx < devCol.Count; devIdx++)
            {
                for (int sesIdx = 0; sesIdx < devCol[devIdx].AudioSessionManager2.Sessions.Count; sesIdx++)
                {
                    if (devCol[devIdx].AudioSessionManager2.Sessions[sesIdx].GetSessionIdentifier.Contains(appName))
                        devicesAndSessions.Add(new KeyValuePair<int, int>(devIdx, sesIdx));
                }
            }
        }
예제 #40
0
파일: Mute.cs 프로젝트: SresgaminG/ArmamutE
        public static List<string> GetListOfApplicationsWithAudio()
        {
            List<string> results = new List<string>();

            EDataFlow flow = new EDataFlow();
            MMDeviceEnumerator deviceEnum = new MMDeviceEnumerator();

            devCol = deviceEnum.EnumerateAudioEndPoints(flow, DEVICE_STATE.DEVICE_STATE_ACTIVE);

            for (int devIdx = 0; devIdx < devCol.Count; devIdx++)
            {
                for (int sesIdx = 0; sesIdx < devCol[devIdx].AudioSessionManager2.Sessions.Count; sesIdx++)
                {
                    results.Add(devCol[devIdx].AudioSessionManager2.Sessions[sesIdx].GetSessionIdentifier);
                }
            }

            return results;
        }
예제 #41
0
        internal static void RefreshDevices(EDataFlow renderType, bool updateIcons)
        {
            DeviceNames.Clear();
            DeviceIDs.Clear();

            if (updateIcons)
                DeviceIcons.Clear();

            var pDevices = pEnum.EnumerateAudioEndPoints(renderType, EDeviceState.DEVICE_STATE_ACTIVE);
            var devCount = pDevices.Count;

            for (var i = 0; i < devCount; i++)
            {
                var device = pDevices[i];
                DeviceNames.Add(device.FriendlyName);
                DeviceIDs.Add(i, device.ID);

                if (updateIcons)
                    DeviceIcons.Add(device.IconPath);
            }           
        }
예제 #42
0
파일: Mute.cs 프로젝트: SresgaminG/ArmamutE
        private static void FindApplication(string appName)
        {
            LogHelper.Debug(null, "Finding any mixers that contain the word '{0}'", appName);

            EDataFlow flow = new EDataFlow();
            MMDeviceEnumerator deviceEnum = new MMDeviceEnumerator();

            devCol = deviceEnum.EnumerateAudioEndPoints(flow, DEVICE_STATE.DEVICE_STATE_ACTIVE);

            for (int devIdx = 0; devIdx < devCol.Count; devIdx++)
            {
                for (int sesIdx = 0; sesIdx < devCol[devIdx].AudioSessionManager2.Sessions.Count; sesIdx++)
                {
                    if (devCol[devIdx].AudioSessionManager2.Sessions[sesIdx].GetSessionIdentifier.Contains(appName))
                    {
                        LogHelper.Debug(null, "Found {0}", devCol[devIdx].AudioSessionManager2.Sessions[sesIdx].GetSessionIdentifier);

                        devicesAndSessions.Add(new KeyValuePair<int, int>(devIdx, sesIdx));
                    }
                }
            }
        }
예제 #43
0
        internal static void RefreshDeviceList(EDataFlow renderType)
        {
            DeviceNames.Clear();
            DeviceIDs.Clear();

            var pDevices = DeviceEnumerator.EnumerateAudioEndPoints(renderType, EDeviceState.Active);
            var defDeviceID = DeviceEnumerator.GetDefaultAudioEndpoint(renderType, ERole.eMultimedia).ID;
            var devCount = pDevices.Count;

            for (var i = 0; i < devCount; i++)
            {
                var device = pDevices[i];
                var devID = device.ID;
                var devName = device.FriendlyName;
                DeviceNames.Add(devID, devName);
                DeviceIDs.Add(i, devID);

                if (devID == defDeviceID)
                {
                    DefaultDeviceID = i;
                    DefaultDeviceName = devName;
                }
            }
        }
예제 #44
0
        private void ChangeDeviceState(EDataFlow rType, bool toggleMute, int volChange, bool showOSD)
        {
            var MMDevice = EndPoints.GetDefaultMMDevice(rType);
            if (toggleMute)
            {
                var mute = MMDevice.AudioEndpointVolume.Mute = !MMDevice.AudioEndpointVolume.Mute;
                if (showOSD)
                    Program.frmOSD.ChangeMute(mute, MMDevice.AudioEndpointVolume.MasterVolumeLevelScalar);
            }
            else if (volChange != 0)
            {
                var vol = CalcVol(MMDevice.AudioEndpointVolume.MasterVolumeLevelScalar, volChange);
                MMDevice.AudioEndpointVolume.MasterVolumeLevelScalar = vol;

                if (showOSD)
                    Program.frmOSD.ChangeVolume(vol);
            }
        }
예제 #45
0
        private void notifyIcon1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if (Program.settings.QuickSwitchEnabled && !DeactivatedOnIcon)
                {
                    notifyIcon.ContextMenuStrip = null;
                    QuickSwitchDevice(false, Program.settings.DefaultDataFlow, Program.settings.QuickSwitchShowOSD);
                }
                else
                    notifyIcon.ContextMenuStrip = trayMenu;

                return;
            }

            var rType = Program.settings.DefaultDataFlow;
            if (ModifierKeys.HasFlag(Keys.Control))
                rType = rType == EDataFlow.eRender ? EDataFlow.eCapture : EDataFlow.eRender;

            RenderType = rType;
            RefreshDevices(RenderType);

            if (DeactivatedOnIcon)
                return;

            SetSizes();
        }
예제 #46
0
        private void RefreshDevices(EDataFlow renderType)
        {
            listDevices.Clear();
            DeviceIcons.Clear();

            listDevices.BeginUpdate();

            var pDevices = EndPoints.DeviceEnumerator.EnumerateAudioEndPoints(renderType, EDeviceState.Active);
            if (pDevices.Count > 0)
            {
                var defaultDev = EndPoints.DeviceEnumerator.GetDefaultAudioEndpoint(renderType, ERole.eMultimedia).ID;
                var devCount = pDevices.Count;

                for (var i = 0; i < devCount; i++)
                {
                    var device = pDevices[i];
                    var devID = device.ID;

                    DeviceIcons.Add(device.IconPath);
                    var devSettings = Program.settings.Device.Find(x => x.DeviceID == devID);
                    if (devSettings == null || !devSettings.HideFromList)
                    {
                        var item = new ListViewItem
                        {
                            ImageIndex = i,
                            Text = device.FriendlyName,
                            Selected = devID == defaultDev,
                            Tag = devID,
                        };

                        listDevices.Items.Add(item);

                        if (devID == defaultDev)
                        {
                            SetDeviceIcon(i, true);
                            SetTrayIcons();
                        }
                    }
                }
            }

            listDevices.EndUpdate();
        }
예제 #47
0
        private void notifyIcon1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
                return;

            var rType = Program.settings.DefaultDataFlow;
            if (ModifierKeys.HasFlag(Keys.Control))
                rType = rType == EDataFlow.eRender ? EDataFlow.eCapture : EDataFlow.eRender;

            if (ModifierKeys.HasFlag(Keys.Alt))
            {
                ChangeDeviceState(rType, true, 0, true);
            }
            else
            {
                RenderType = rType;
                RefreshDevices(RenderType);

                if (DeactivatedOnIcon)
                    return;

                SetSizes();
            }
        }
예제 #48
0
 internal DeviceInfo(string deviceId, string name, EDataFlow flow, DeviceState state, WAVEFORMATEXTENSIBLE format)
 {
     _deviceId = deviceId;
     _friendlyName = name;
     _dataFlow = flow;
     _state = state;
     _format = new WAVEFORMATEXTENSIBLE(format);
 }
예제 #49
0
 public void OnDefaultDeviceChanged(EDataFlow flow, ERole role, string defaultDeviceId)
 {
     throw new NotImplementedException();
 }
예제 #50
0
 internal static MMDevice GetDefaultMMDevice(EDataFlow renderType)
 {
     return DeviceEnumerator.GetDefaultAudioEndpoint(renderType, ERole.eMultimedia);
 }
예제 #51
0
        internal void RegisterDevice(EDataFlow RenderType)
        {
            if (EndPoints.DeviceNames.Count == 0) return;

            Device = EndPoints.pEnum.GetDefaultAudioEndpoint(RenderType, ERole.eMultimedia);
            Value = Device.AudioEndpointVolume.MasterVolumeLevelScalar;
            Mute = Device.AudioEndpointVolume.Mute;
            Stereo = Device.AudioMeterInformation.Channels.GetCount() > 1;
            Device.AudioSessionManager.Sessions[0].RegisterAudioSessionNotification(volEvents);
            Device.AudioEndpointVolume.OnVolumeNotification += VolNotify;
        }
예제 #52
0
 internal void RegisterDevice(EDataFlow RenderType)
 {
     Device = EndPoints.DeviceEnumerator.GetDefaultAudioEndpoint(RenderType, ERole.eMultimedia);
     Value = Device.AudioEndpointVolume.MasterVolumeLevelScalar;
     Mute = Device.AudioEndpointVolume.Mute;
     Stereo = Device.AudioMeterInformation.Channels.GetCount() > 1;
     Device.AudioEndpointVolume.OnVolumeNotification += VolNotify;
 }
        public void loadFromXML(XmlTextReader aXMLTextReader)
        {
            var lReader     = new XMLAttributeReader(aXMLTextReader);
                var lChecker    = new RepeatItemNameChecker();

                string lItem    = lReader.getAttribute<String>("ArrayItem");
                lChecker.addItemName(lItem);
                mArrayValueItemHandle = mItemBrowser.getItemHandleByName(lItem);

                mDataFlow = (EDataFlow)Enum.Parse(typeof(EDataFlow), lReader.getAttribute<String>("DataFlow", mDataFlow.ToString()));

                #region Elements

                    if (aXMLTextReader.IsEmptyElement == false)
                    {
                        aXMLTextReader.Read();
                        if (aXMLTextReader.Name.Equals("Elements", StringComparison.Ordinal))
                        {
                            if (aXMLTextReader.IsEmptyElement == false)
                            {
                                List<int> lIndexes  = new List<int>();
                                List<int> lItems    = new List<int>();
                                var lIndexSet       = new HashSet<int>();
                                int lMaxIndex       = -1;
                                int lIndex;

                                aXMLTextReader.Read();
                                while (aXMLTextReader.Name.Equals("Element", StringComparison.Ordinal))
                                {
                                    lIndex = (int)lReader.getAttribute<UInt32>("Index");
                                    if (lIndexSet.Add(lIndex) == false)
                                    {
                                        throw new ArgumentException("Index '" + lIndex.ToString() + "' already exists. ");
                                    }
                                    lIndexes.Add(lIndex);
                                    if (lIndex > lMaxIndex)
                                    {
                                        lMaxIndex = lIndex;
                                    }

                                    lItem = lReader.getAttribute<String>("Item");
                                    lChecker.addItemName(lItem);
                                    lItems.Add(mItemBrowser.getItemHandleByName(lItem));

                                    aXMLTextReader.Read();
                                }

                                if (lIndexes.Count != 0)
                                {
                                    mElementItemHandles = new int[lMaxIndex + 1];
                                    for (int i = 0; i < mElementItemHandles.Length; i++)
                                    {
                                        mElementItemHandles[i] = -1;
                                    }
                                    mElementValueChanged    = new bool[mElementItemHandles.Length];
                                    mArrayValue             = new object[mElementItemHandles.Length];

                                    int lCount = lIndexes.Count;
                                    for (int i = 0; i < lCount; i++)
                                    {
                                        lIndex                      = lIndexes[i];
                                        mElementItemHandles[lIndex] = lItems[i];
                                    }
                                }
                            }

                            aXMLTextReader.Read();
                        }
                    }

                #endregion
        }
예제 #54
0
        private void FormSwitcher_Deactivate(object sender, EventArgs e)
        {
            Hide();
            timer1.Enabled = false;
            RenderType = Program.settings.DefaultDataFlow;
            RefreshDevices(RenderType);
            VolBar.RegisterDevice(RenderType);

            var iconpos = WindowPosition.GetNotifyIconArea(notifyIcon);
            var iconrect = new Rectangle(iconpos.left, iconpos.top, iconpos.right - iconpos.left, iconpos.bottom - iconpos.top);

            if (iconrect.Contains(Cursor.Position))
                DeactivatedOnIcon = true;
        }
예제 #55
0
        private void notifyIcon1_MouseDown(object sender, MouseEventArgs e)
        {
            if (ModifierKeys == Keys.Shift)
            {
                Close();
                Application.Exit();
                return;
            }

            VolBar.UnregisterDevice();
            RenderType = ModifierKeys.HasFlag(Keys.Control) ? EDataFlow.eCapture : EDataFlow.eRender;

            if (ModifierKeys.HasFlag(Keys.Alt))
            {
                RefreshDevices(false);
                VolBar.RegisterDevice(RenderType);
                VolBar.ChangeMute();
                VolBar.UnregisterDevice();

                if (RenderType == EDataFlow.eCapture && !Program.stfu)
                {
                    var mutetxt = String.Format("Device {0}muted", VolBar.Mute ? "" : "un");
                    notifyIcon.ShowBalloonTip(0, mutetxt, EndPoints.DeviceNames[CurrentDevice], ToolTipIcon.Info);
                }
                
                RenderType = EDataFlow.eRender;
                RefreshDevices(false);
                VolBar.RegisterDevice(RenderType);
                return;
            }
            
            RefreshDevices(true);

            if (e.Button == MouseButtons.Left)
                SetSizes();
        }
 internal MMDeviceCollection(IMMDeviceCollection parent, EDataFlow flow, EDeviceState state)
 {
     _MMDeviceCollection = parent;
     DataFlow = flow;
     DeviceState = state;
 }
예제 #57
0
        private void QuickSwitchDevice(bool previous, EDataFlow rType, bool showOSD)
        {
            var devName = previous ? EndPoints.SetPrevDefault(rType) : EndPoints.SetNextDefault(rType);

            if (showOSD)
                Program.frmOSD.ChangeDevice(devName);
        }
예제 #58
0
        private void HotKeyPressed()
        {
            if (Visible) return; // Let's not make it complicated here...

            VolBar.UnregisterDevice();
            RenderType = EDataFlow.eRender;
            RefreshDevices(false);
            if (EndPoints.DeviceNames.Count == 0) return;

            CurrentDevice = CurrentDevice == EndPoints.DeviceNames.Count - 1 ? 0 : CurrentDevice + 1;
            EndPoints.SetDefaultDevice(CurrentDevice);
            if (!Program.stfu)
                notifyIcon.ShowBalloonTip(0, "Audio device changed", EndPoints.DeviceNames[CurrentDevice], ToolTipIcon.Info);
        }
예제 #59
0
 private void settingsToolStripMenuItem_Click(object sender, EventArgs e)
 {
     using (var cfg = new FormSettings())
     {
         RenderType = Program.settings.DefaultDataFlow;
         RefreshDevices(RenderType);
         cfg.ShowDialog();
         ledLeft.OldStyle = Program.settings.ColorVU;
         ledRight.OldStyle = Program.settings.ColorVU;
         SetTrayIcons();
     }
 }
예제 #60
0
 public void OnDefaultDeviceChanged(EDataFlow flow, ERole role, string defaultDeviceId)
 {
     var inner = GetInner();
     if(inner != null)
         inner.OnDefaultDeviceChanged(flow, role, defaultDeviceId);
 }