public SensorNotifyIcon(SystemTray sensorSystemTray, ISensor sensor, PersistentSettings settings, UnitManager unitManager)
        {
            _unitManager = unitManager;
            Sensor       = sensor;
            _notifyIcon  = new NotifyIconAdv();

            Color defaultColor = Color.White;

            if (sensor.SensorType == SensorType.Load || sensor.SensorType == SensorType.Control || sensor.SensorType == SensorType.Level)
            {
                defaultColor = Color.FromArgb(0xff, 0x70, 0x8c, 0xf1);
            }

            Color = settings.GetValue(new Identifier(sensor.Identifier, "traycolor").ToString(), defaultColor);

            _pen = new Pen(Color.FromArgb(96, Color.Black));
            ContextMenuStrip contextMenuStrip = new ContextMenuStrip();
            ToolStripItem    hideShowItem     = new ToolStripMenuItem("Hide/Show");

            hideShowItem.Click += delegate
            {
                sensorSystemTray.SendHideShowCommand();
            };
            contextMenuStrip.Items.Add(hideShowItem);
            contextMenuStrip.Items.Add(new ToolStripSeparator());
            ToolStripItem removeItem = new ToolStripMenuItem("Remove Sensor");

            removeItem.Click += delegate
            {
                sensorSystemTray.Remove(Sensor);
            };
            contextMenuStrip.Items.Add(removeItem);
            ToolStripItem colorItem = new ToolStripMenuItem("Change Color...");

            colorItem.Click += delegate
            {
                ColorDialog dialog = new ColorDialog {
                    Color = Color
                };
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    Color = dialog.Color;
                    settings.SetValue(new Identifier(sensor.Identifier,
                                                     "traycolor").ToString(), Color);
                }
            };
            contextMenuStrip.Items.Add(colorItem);
            contextMenuStrip.Items.Add(new ToolStripSeparator());
            ToolStripItem exitItem = new ToolStripMenuItem("Exit");

            exitItem.Click += delegate
            {
                sensorSystemTray.SendExitCommand();
            };
            contextMenuStrip.Items.Add(exitItem);
            _notifyIcon.ContextMenuStrip = contextMenuStrip;
            _notifyIcon.DoubleClick     += delegate
            {
                sensorSystemTray.SendHideShowCommand();
            };

            // get the default dpi to create an icon with the correct size
            float dpiX, dpiY;

            using (Bitmap b = new Bitmap(1, 1, PixelFormat.Format32bppArgb))
            {
                dpiX = b.HorizontalResolution;
                dpiY = b.VerticalResolution;
            }

            // adjust the size of the icon to current dpi (default is 16x16 at 96 dpi)
            int width  = (int)Math.Round(16 * dpiX / 96);
            int height = (int)Math.Round(16 * dpiY / 96);

            // make sure it does never get smaller than 16x16
            width  = width < 16 ? 16 : width;
            height = height < 16 ? 16 : height;

            // adjust the font size to the icon size
            FontFamily family = SystemFonts.MessageBoxFont.FontFamily;
            float      baseSize;

            switch (family.Name)
            {
            case "Segoe UI": baseSize = 12; break;

            case "Tahoma": baseSize = 11; break;

            default: baseSize = 12; break;
            }

            _font      = new Font(family, baseSize * width / 16.0f, GraphicsUnit.Pixel);
            _smallFont = new Font(family, 0.75f * baseSize * width / 16.0f, GraphicsUnit.Pixel);

            _bitmap   = new Bitmap(width, height, PixelFormat.Format32bppArgb);
            _graphics = Graphics.FromImage(_bitmap);
            if (Environment.OSVersion.Version.Major > 5)
            {
                _graphics.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
                _graphics.SmoothingMode     = SmoothingMode.HighQuality;
            }
        }
        public void Update()
        {
            Icon icon = _notifyIcon.Icon;

            switch (Sensor.SensorType)
            {
            case SensorType.Load:
            case SensorType.Control:
            case SensorType.Level:
                _notifyIcon.Icon = CreatePercentageIcon();
                break;

            default:
                _notifyIcon.Icon = CreateTransparentIcon();
                break;
            }

            icon?.Destroy();

            string format = "";

            switch (Sensor.SensorType)
            {
            case SensorType.Voltage: format = "\n{0}: {1:F2} V"; break;

            case SensorType.Current: format = "\n{0}: {1:F2} A"; break;

            case SensorType.Clock: format = "\n{0}: {1:F0} MHz"; break;

            case SensorType.Load: format = "\n{0}: {1:F1} %"; break;

            case SensorType.Temperature: format = "\n{0}: {1:F1} °C"; break;

            case SensorType.Fan: format = "\n{0}: {1:F0} RPM"; break;

            case SensorType.Flow: format = "\n{0}: {1:F0} L/h"; break;

            case SensorType.Control: format = "\n{0}: {1:F1} %"; break;

            case SensorType.Level: format = "\n{0}: {1:F1} %"; break;

            case SensorType.Power: format = "\n{0}: {1:F0} W"; break;

            case SensorType.Data: format = "\n{0}: {1:F0} GB"; break;

            case SensorType.Factor: format = "\n{0}: {1:F3} GB"; break;
            }
            string formattedValue = string.Format(format, Sensor.Name, Sensor.Value);

            if (Sensor.SensorType == SensorType.Temperature && _unitManager.TemperatureUnit == TemperatureUnit.Fahrenheit)
            {
                format         = "\n{0}: {1:F1} °F";
                formattedValue = string.Format(format, Sensor.Name, UnitManager.CelsiusToFahrenheit(Sensor.Value));
            }

            string hardwareName = Sensor.Hardware.Name;

            hardwareName = hardwareName.Substring(0, Math.Min(63 - formattedValue.Length, hardwareName.Length));
            string text = hardwareName + formattedValue;

            if (text.Length > 63)
            {
                text = null;
            }

            _notifyIcon.Text    = text;
            _notifyIcon.Visible = true;
        }
        private string GetString()
        {
            if (!Sensor.Value.HasValue)
            {
                return("-");
            }

            switch (Sensor.SensorType)
            {
            case SensorType.Voltage:
                return($"{Sensor.Value:F1}");

            case SensorType.Current:
                return($"{Sensor.Value:F1}");

            case SensorType.Clock:
                return($"{1e-3f * Sensor.Value:F1}");

            case SensorType.Load:
                return($"{Sensor.Value:F0}");

            case SensorType.Temperature:
                return(_unitManager.TemperatureUnit == TemperatureUnit.Fahrenheit ? $"{UnitManager.CelsiusToFahrenheit(Sensor.Value):F0}" : $"{Sensor.Value:F0}");

            case SensorType.Fan:
                return($"{1e-3f * Sensor.Value:F1}");

            case SensorType.Flow:
                return($"{1e-3f * Sensor.Value:F1}");

            case SensorType.Control:
                return($"{Sensor.Value:F0}");

            case SensorType.Level:
                return($"{Sensor.Value:F0}");

            case SensorType.Power:
                return($"{Sensor.Value:F0}");

            case SensorType.Data:
                return($"{Sensor.Value:F0}");

            case SensorType.Factor:
                return($"{Sensor.Value:F1}");
            }
            return("-");
        }
Пример #4
0
        public MainForm()
        {
            InitializeComponent();

            // check if the LibreHardwareMonitorLib assembly has the correct version
            if (Assembly.GetAssembly(typeof(Computer)).GetName().Version != Assembly.GetExecutingAssembly().GetName().Version)
            {
                MessageBox.Show("The version of the file LibreHardwareMonitorLib.dll is incompatible.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Environment.Exit(0);
            }

            _settings = new PersistentSettings();
            _settings.Load(Path.ChangeExtension(Application.ExecutablePath, ".config"));

            _unitManager = new UnitManager(_settings);

            // make sure the buffers used for double buffering are not disposed
            // after each draw call
            BufferedGraphicsManager.Current.MaximumBuffer = Screen.PrimaryScreen.Bounds.Size;

            // set the DockStyle here, to avoid conflicts with the MainMenu
            splitContainer.Dock = DockStyle.Fill;

            Font          = SystemFonts.MessageBoxFont;
            treeView.Font = SystemFonts.MessageBoxFont;

            // Set the bounds immediately, so that our child components can be
            // properly placed.
            Bounds = new Rectangle
            {
                X      = _settings.GetValue("mainForm.Location.X", Location.X),
                Y      = _settings.GetValue("mainForm.Location.Y", Location.Y),
                Width  = _settings.GetValue("mainForm.Width", 470),
                Height = _settings.GetValue("mainForm.Height", 640)
            };

            _plotPanel = new PlotPanel(_settings, _unitManager)
            {
                Font = SystemFonts.MessageBoxFont, Dock = DockStyle.Fill
            };

            nodeCheckBox.IsVisibleValueNeeded += NodeCheckBox_IsVisibleValueNeeded;
            nodeTextBoxText.DrawText          += NodeTextBoxText_DrawText;
            nodeTextBoxValue.DrawText         += NodeTextBoxText_DrawText;
            nodeTextBoxMin.DrawText           += NodeTextBoxText_DrawText;
            nodeTextBoxMax.DrawText           += NodeTextBoxText_DrawText;
            nodeTextBoxText.EditorShowing     += NodeTextBoxText_EditorShowing;

            foreach (TreeColumn column in treeView.Columns)
            {
                column.Width = Math.Max(20, Math.Min(400, _settings.GetValue("treeView.Columns." + column.Header + ".Width", column.Width)));
            }

            TreeModel treeModel = new TreeModel();

            _root = new Node(Environment.MachineName)
            {
                Image = EmbeddedResources.GetImage("computer.png")
            };

            treeModel.Nodes.Add(_root);
            treeView.Model = treeModel;

            _computer = new Computer(_settings);

            _systemTray = new SystemTray(_computer, _settings, _unitManager);
            _systemTray.HideShowCommand += HideShowClick;
            _systemTray.ExitCommand     += ExitClick;

            if (Software.OperatingSystem.IsUnix)
            {
                // Unix
                treeView.RowHeight           = Math.Max(treeView.RowHeight, 18);
                splitContainer.BorderStyle   = BorderStyle.None;
                splitContainer.Border3DStyle = Border3DStyle.Adjust;
                splitContainer.SplitterWidth = 4;
                treeView.BorderStyle         = BorderStyle.Fixed3D;
                _plotPanel.BorderStyle       = BorderStyle.Fixed3D;
                gadgetMenuItem.Visible       = false;
                minCloseMenuItem.Visible     = false;
                minTrayMenuItem.Visible      = false;
                startMinMenuItem.Visible     = false;
            }
            else
            { // Windows
                treeView.RowHeight       = Math.Max(treeView.Font.Height + 1, 18);
                _gadget                  = new SensorGadget(_computer, _settings, _unitManager);
                _gadget.HideShowCommand += HideShowClick;
                _wmiProvider             = new WmiProvider(_computer);
            }

            _logger = new Logger(_computer);

            _plotColorPalette     = new Color[13];
            _plotColorPalette[0]  = Color.Blue;
            _plotColorPalette[1]  = Color.OrangeRed;
            _plotColorPalette[2]  = Color.Green;
            _plotColorPalette[3]  = Color.LightSeaGreen;
            _plotColorPalette[4]  = Color.Goldenrod;
            _plotColorPalette[5]  = Color.DarkViolet;
            _plotColorPalette[6]  = Color.YellowGreen;
            _plotColorPalette[7]  = Color.SaddleBrown;
            _plotColorPalette[8]  = Color.RoyalBlue;
            _plotColorPalette[9]  = Color.DeepPink;
            _plotColorPalette[10] = Color.MediumSeaGreen;
            _plotColorPalette[11] = Color.Olive;
            _plotColorPalette[12] = Color.Firebrick;

            _computer.HardwareAdded   += HardwareAdded;
            _computer.HardwareRemoved += HardwareRemoved;
            _computer.Open();

            timer.Enabled = true;

            UserOption showHiddenSensors = new UserOption("hiddenMenuItem", false, hiddenMenuItem, _settings);

            showHiddenSensors.Changed += delegate
            {
                treeModel.ForceVisible = showHiddenSensors.Value;
            };

            UserOption showValue = new UserOption("valueMenuItem", true, valueMenuItem, _settings);

            showValue.Changed += delegate
            {
                treeView.Columns[1].IsVisible = showValue.Value;
            };

            UserOption showMin = new UserOption("minMenuItem", false, minMenuItem, _settings);

            showMin.Changed += delegate
            {
                treeView.Columns[2].IsVisible = showMin.Value;
            };

            UserOption showMax = new UserOption("maxMenuItem", true, maxMenuItem, _settings);

            showMax.Changed += delegate
            {
                treeView.Columns[3].IsVisible = showMax.Value;
            };

            var _ = new UserOption("startMinMenuItem", false, startMinMenuItem, _settings);

            _minimizeToTray          = new UserOption("minTrayMenuItem", true, minTrayMenuItem, _settings);
            _minimizeToTray.Changed += delegate
            {
                _systemTray.IsMainIconEnabled = _minimizeToTray.Value;
            };

            _minimizeOnClose = new UserOption("minCloseMenuItem", false, minCloseMenuItem, _settings);

            _autoStart          = new UserOption(null, _startupManager.Startup, startupMenuItem, _settings);
            _autoStart.Changed += delegate
            {
                try
                {
                    _startupManager.Startup = _autoStart.Value;
                }
                catch (InvalidOperationException)
                {
                    MessageBox.Show("Updating the auto-startup option failed.", "Error",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                    _autoStart.Value = _startupManager.Startup;
                }
            };

            _readMainboardSensors          = new UserOption("mainboardMenuItem", true, mainboardMenuItem, _settings);
            _readMainboardSensors.Changed += delegate
            {
                _computer.IsMotherboardEnabled = _readMainboardSensors.Value;
            };

            _readCpuSensors          = new UserOption("cpuMenuItem", true, cpuMenuItem, _settings);
            _readCpuSensors.Changed += delegate
            {
                _computer.IsCpuEnabled = _readCpuSensors.Value;
            };

            _readRamSensors          = new UserOption("ramMenuItem", true, ramMenuItem, _settings);
            _readRamSensors.Changed += delegate
            {
                _computer.IsMemoryEnabled = _readRamSensors.Value;
            };

            _readGpuSensors          = new UserOption("gpuMenuItem", true, gpuMenuItem, _settings);
            _readGpuSensors.Changed += delegate
            {
                _computer.IsGpuEnabled = _readGpuSensors.Value;
            };

            _readFanControllersSensors          = new UserOption("fanControllerMenuItem", true, fanControllerMenuItem, _settings);
            _readFanControllersSensors.Changed += delegate
            {
                _computer.IsControllerEnabled = _readFanControllersSensors.Value;
            };

            _readHddSensors          = new UserOption("hddMenuItem", true, hddMenuItem, _settings);
            _readHddSensors.Changed += delegate
            {
                _computer.IsStorageEnabled = _readHddSensors.Value;
            };

            _readNicSensors          = new UserOption("nicMenuItem", true, nicMenuItem, _settings);
            _readNicSensors.Changed += delegate
            {
                _computer.IsNetworkEnabled = _readNicSensors.Value;
            };

            _showGadget          = new UserOption("gadgetMenuItem", false, gadgetMenuItem, _settings);
            _showGadget.Changed += delegate
            {
                if (_gadget != null)
                {
                    _gadget.Visible = _showGadget.Value;
                }
            };

            celsiusMenuItem.Checked    = _unitManager.TemperatureUnit == TemperatureUnit.Celsius;
            fahrenheitMenuItem.Checked = !celsiusMenuItem.Checked;

            Server = new HttpServer(_root, _settings.GetValue("listenerPort", 8085), _settings.GetValue("authenticationEnabled", false), _settings.GetValue("authenticationUserName", ""), _settings.GetValue("authenticationPassword", ""));
            if (Server.PlatformNotSupported)
            {
                webMenuItemSeparator.Visible = false;
                webMenuItem.Visible          = false;
            }

            _runWebServer          = new UserOption("runWebServerMenuItem", false, runWebServerMenuItem, _settings);
            _runWebServer.Changed += delegate
            {
                if (_runWebServer.Value)
                {
                    Server.StartHttpListener();
                }
                else
                {
                    Server.StopHttpListener();
                }
            };

            authWebServerMenuItem.Checked = _settings.GetValue("authenticationEnabled", false);

            _logSensors = new UserOption("logSensorsMenuItem", false, logSensorsMenuItem, _settings);

            _loggingInterval = new UserRadioGroup("loggingInterval", 0,
                                                  new[] { log1sMenuItem, log2sMenuItem, log5sMenuItem, log10sMenuItem,
                                                          log30sMenuItem, log1minMenuItem, log2minMenuItem, log5minMenuItem,
                                                          log10minMenuItem, log30minMenuItem, log1hMenuItem, log2hMenuItem,
                                                          log6hMenuItem }, _settings);
            _loggingInterval.Changed += (sender, e) =>
            {
                switch (_loggingInterval.Value)
                {
                case 0: _logger.LoggingInterval = new TimeSpan(0, 0, 1); break;

                case 1: _logger.LoggingInterval = new TimeSpan(0, 0, 2); break;

                case 2: _logger.LoggingInterval = new TimeSpan(0, 0, 5); break;

                case 3: _logger.LoggingInterval = new TimeSpan(0, 0, 10); break;

                case 4: _logger.LoggingInterval = new TimeSpan(0, 0, 30); break;

                case 5: _logger.LoggingInterval = new TimeSpan(0, 1, 0); break;

                case 6: _logger.LoggingInterval = new TimeSpan(0, 2, 0); break;

                case 7: _logger.LoggingInterval = new TimeSpan(0, 5, 0); break;

                case 8: _logger.LoggingInterval = new TimeSpan(0, 10, 0); break;

                case 9: _logger.LoggingInterval = new TimeSpan(0, 30, 0); break;

                case 10: _logger.LoggingInterval = new TimeSpan(1, 0, 0); break;

                case 11: _logger.LoggingInterval = new TimeSpan(2, 0, 0); break;

                case 12: _logger.LoggingInterval = new TimeSpan(6, 0, 0); break;
                }
            };

            _sensorValuesTimeWindow = new UserRadioGroup("sensorValuesTimeWindow", 10,
                                                         new[] { timeWindow30sMenuItem, timeWindow1minMenuItem, timeWindow2minMenuItem,
                                                                 timeWindow5minMenuItem, timeWindow10minMenuItem, timeWindow30minMenuItem,
                                                                 timeWindow1hMenuItem, timeWindow2hMenuItem, timeWindow6hMenuItem,
                                                                 timeWindow12hMenuItem, timeWindow24hMenuItem }, _settings);
            _sensorValuesTimeWindow.Changed += (sender, e) =>
            {
                TimeSpan timeWindow = TimeSpan.Zero;
                switch (_sensorValuesTimeWindow.Value)
                {
                case 0: timeWindow = new TimeSpan(0, 0, 30); break;

                case 1: timeWindow = new TimeSpan(0, 1, 0); break;

                case 2: timeWindow = new TimeSpan(0, 2, 0); break;

                case 3: timeWindow = new TimeSpan(0, 5, 0); break;

                case 4: timeWindow = new TimeSpan(0, 10, 0); break;

                case 5: timeWindow = new TimeSpan(0, 30, 0); break;

                case 6: timeWindow = new TimeSpan(1, 0, 0); break;

                case 7: timeWindow = new TimeSpan(2, 0, 0); break;

                case 8: timeWindow = new TimeSpan(6, 0, 0); break;

                case 9: timeWindow = new TimeSpan(12, 0, 0); break;

                case 10: timeWindow = new TimeSpan(24, 0, 0); break;
                }

                _computer.Accept(new SensorVisitor(delegate(ISensor sensor)
                {
                    sensor.ValuesTimeWindow = timeWindow;
                }));
            };

            InitializePlotForm();
            InitializeSplitter();

            startupMenuItem.Visible = _startupManager.IsAvailable;

            if (startMinMenuItem.Checked)
            {
                if (!minTrayMenuItem.Checked)
                {
                    WindowState = FormWindowState.Minimized;
                    Show();
                }
            }
            else
            {
                Show();
            }

            // Create a handle, otherwise calling Close() does not fire FormClosed

            // Make sure the settings are saved when the user logs off
            Microsoft.Win32.SystemEvents.SessionEnded += delegate
            {
                _computer.Close();
                SaveConfiguration();
                if (_runWebServer.Value)
                {
                    Server.Quit();
                }
            };

            Microsoft.Win32.SystemEvents.PowerModeChanged += PowerModeChanged;
        }
Пример #5
0
        protected override void OnPaint(PaintEventArgs e)
        {
            Graphics g = e.Graphics;
            int      w = Size.Width;

            g.Clear(Color.Transparent);
            DrawBackground(g);

            int x;
            int y = _topMargin;

            if (_sensors.Count == 0)
            {
                x = LeftBorder + 1;
                g.DrawString("Right-click on a sensor in the main window and select " +
                             "\"Show in Gadget\" to show the sensor here.",
                             _smallFont, Brushes.White,
                             new Rectangle(x, y - 1, w - RightBorder - x, 0));
            }

            foreach (KeyValuePair <IHardware, IList <ISensor> > pair in _sensors)
            {
                if (_hardwareNames.Value)
                {
                    if (y > _topMargin)
                    {
                        y += _hardwareLineHeight - _sensorLineHeight;
                    }
                    x = LeftBorder + 1;
                    g.DrawImage(HardwareTypeImage.Instance.GetImage(pair.Key.HardwareType), new Rectangle(x, y + 1, _iconSize, _iconSize));
                    x += _iconSize + 1;
                    g.DrawString(pair.Key.Name, _largeFont, Brushes.White, new Rectangle(x, y - 1, w - RightBorder - x, 0), _stringFormat);
                    y += _hardwareLineHeight;
                }

                foreach (ISensor sensor in pair.Value)
                {
                    int remainingWidth;


                    if ((sensor.SensorType != SensorType.Load &&
                         sensor.SensorType != SensorType.Control &&
                         sensor.SensorType != SensorType.Level) || !sensor.Value.HasValue)
                    {
                        string formatted;

                        if (sensor.Value.HasValue)
                        {
                            string format = "";
                            switch (sensor.SensorType)
                            {
                            case SensorType.Voltage:
                                format = "{0:F3} V";
                                break;

                            case SensorType.Clock:
                                format = "{0:F0} MHz";
                                break;

                            case SensorType.Frequency:
                                format = "{0:F0} Hz";
                                break;

                            case SensorType.Temperature:
                                format = "{0:F1} °C";
                                break;

                            case SensorType.Fan:
                                format = "{0:F0} RPM";
                                break;

                            case SensorType.Flow:
                                format = "{0:F0} L/h";
                                break;

                            case SensorType.Power:
                                format = "{0:F1} W";
                                break;

                            case SensorType.Data:
                                format = "{0:F1} GB";
                                break;

                            case SensorType.SmallData:
                                format = "{0:F0} MB";
                                break;

                            case SensorType.Factor:
                                format = "{0:F3}";
                                break;
                            }

                            if (sensor.SensorType == SensorType.Temperature && _unitManager.TemperatureUnit == TemperatureUnit.Fahrenheit)
                            {
                                formatted = $"{UnitManager.CelsiusToFahrenheit(sensor.Value):F1} °F";
                            }
                            else if (sensor.SensorType == SensorType.Throughput)
                            {
                                string result;
                                switch (sensor.Name)
                                {
                                case "Connection Speed":
                                {
                                    switch (sensor.Value)
                                    {
                                    case 100000000:
                                        result = "100Mbps";
                                        break;

                                    case 1000000000:
                                        result = "1Gbps";
                                        break;

                                    default:
                                    {
                                        if (sensor.Value < 1024)
                                        {
                                            result = $"{sensor.Value:F0} bps";
                                        }
                                        else if (sensor.Value < 1048576)
                                        {
                                            result = $"{sensor.Value / 1024:F1} Kbps";
                                        }
                                        else if (sensor.Value < 1073741824)
                                        {
                                            result = $"{sensor.Value / 1048576:F1} Mbps";
                                        }
                                        else
                                        {
                                            result = $"{sensor.Value / 1073741824:F1} Gbps";
                                        }
                                    }
                                    break;
                                    }
                                }
                                break;

                                default:
                                {
                                    if (sensor.Value < 1048576)
                                    {
                                        result = $"{sensor.Value / 1024:F1} KB/s";
                                    }
                                    else
                                    {
                                        result = $"{sensor.Value / 1048576:F1} MB/s";
                                    }
                                }
                                break;
                                }
                                formatted = result;
                            }
                            else
                            {
                                formatted = string.Format(format, sensor.Value);
                            }
                        }
                        else
                        {
                            formatted = "-";
                        }

                        g.DrawString(formatted, _smallFont, _darkWhite, new RectangleF(-1, y - 1, w - _rightMargin + 3, 0), _alignRightStringFormat);

                        remainingWidth = w - (int)Math.Floor(g.MeasureString(formatted, _smallFont, w, StringFormat.GenericTypographic).Width) - _rightMargin;
                    }
                    else
                    {
                        DrawProgress(g, w - _progressWidth - _rightMargin, y + 0.35f * _sensorLineHeight, _progressWidth, 0.6f * _sensorLineHeight, 0.01f * sensor.Value.Value);
                        remainingWidth = w - _progressWidth - _rightMargin;
                    }

                    remainingWidth -= _leftMargin + 2;
                    if (remainingWidth > 0)
                    {
                        g.DrawString(sensor.Name, _smallFont, _darkWhite, new RectangleF(_leftMargin - 1, y - 1, remainingWidth, 0), _trimStringFormat);
                    }
                    y += _sensorLineHeight;
                }
            }
        }
Пример #6
0
        public SensorGadget(IComputer computer, PersistentSettings settings, UnitManager unitManager)
        {
            _unitManager              = unitManager;
            _settings                 = settings;
            computer.HardwareAdded   += HardwareAdded;
            computer.HardwareRemoved += HardwareRemoved;

            _darkWhite    = new SolidBrush(Color.FromArgb(0xF0, 0xF0, 0xF0));
            _stringFormat = new StringFormat {
                FormatFlags = StringFormatFlags.NoWrap
            };
            _trimStringFormat = new StringFormat {
                Trimming = StringTrimming.EllipsisCharacter, FormatFlags = StringFormatFlags.NoWrap
            };
            _alignRightStringFormat = new StringFormat {
                Alignment = StringAlignment.Far, FormatFlags = StringFormatFlags.NoWrap
            };

            if (File.Exists("gadget_background.png"))
            {
                try
                {
                    Image newBack = new Bitmap("gadget_background.png");
                    _back.Dispose();
                    _back = newBack;
                }
                catch { }
            }

            if (File.Exists("gadget_image.png"))
            {
                try
                {
                    _image = new Bitmap("gadget_image.png");
                }
                catch { }
            }

            if (File.Exists("gadget_foreground.png"))
            {
                try
                {
                    _fore = new Bitmap("gadget_foreground.png");
                }
                catch { }
            }

            if (File.Exists("gadget_bar_background.png"))
            {
                try
                {
                    Image newBarBack = new Bitmap("gadget_bar_background.png");
                    _barBack.Dispose();
                    _barBack = newBarBack;
                }
                catch { }
            }

            if (File.Exists("gadget_bar_foreground.png"))
            {
                try
                {
                    Image newBarColor = new Bitmap("gadget_bar_foreground.png");
                    _barFore.Dispose();
                    _barFore = newBarColor;
                }
                catch { }
            }

            Location         = new Point(settings.GetValue("sensorGadget.Location.X", 100), settings.GetValue("sensorGadget.Location.Y", 100));
            LocationChanged += delegate
            {
                settings.SetValue("sensorGadget.Location.X", Location.X);
                settings.SetValue("sensorGadget.Location.Y", Location.Y);
            };

            // get the custom to default dpi ratio
            using (Bitmap b = new Bitmap(1, 1))
            {
                _scale = b.HorizontalResolution / 96.0f;
            }

            SetFontSize(settings.GetValue("sensorGadget.FontSize", 7.5f));
            Resize(settings.GetValue("sensorGadget.Width", Size.Width));

            ContextMenu contextMenu       = new ContextMenu();
            MenuItem    hardwareNamesItem = new MenuItem("Hardware Names");

            contextMenu.MenuItems.Add(hardwareNamesItem);
            MenuItem fontSizeMenu = new MenuItem("Font Size");

            for (int i = 0; i < 4; i++)
            {
                float  size;
                string name;
                switch (i)
                {
                case 0: size = 6.5f; name = "Small"; break;

                case 1: size = 7.5f; name = "Medium"; break;

                case 2: size = 9f; name = "Large"; break;

                case 3: size = 11f; name = "Very Large"; break;

                default: throw new NotImplementedException();
                }

                MenuItem item = new MenuItem(name)
                {
                    Checked = _fontSize == size
                };
                item.Click += delegate
                {
                    SetFontSize(size);
                    settings.SetValue("sensorGadget.FontSize", size);
                    foreach (MenuItem mi in fontSizeMenu.MenuItems)
                    {
                        mi.Checked = mi == item;
                    }
                };
                fontSizeMenu.MenuItems.Add(item);
            }
            contextMenu.MenuItems.Add(fontSizeMenu);
            contextMenu.MenuItems.Add(new MenuItem("-"));
            MenuItem lockItem = new MenuItem("Lock Position and Size");

            contextMenu.MenuItems.Add(lockItem);
            contextMenu.MenuItems.Add(new MenuItem("-"));
            MenuItem alwaysOnTopItem = new MenuItem("Always on Top");

            contextMenu.MenuItems.Add(alwaysOnTopItem);
            MenuItem opacityMenu = new MenuItem("Opacity");

            contextMenu.MenuItems.Add(opacityMenu);
            Opacity = (byte)settings.GetValue("sensorGadget.Opacity", 255);

            for (int i = 0; i < 5; i++)
            {
                MenuItem item = new MenuItem((20 * (i + 1)).ToString() + " %");
                byte     o    = (byte)(51 * (i + 1));
                item.Checked = Opacity == o;
                item.Click  += delegate
                {
                    Opacity = o;
                    settings.SetValue("sensorGadget.Opacity", Opacity);
                    foreach (MenuItem mi in opacityMenu.MenuItems)
                    {
                        mi.Checked = mi == item;
                    }
                };
                opacityMenu.MenuItems.Add(item);
            }
            ContextMenu = contextMenu;

            _hardwareNames          = new UserOption("sensorGadget.Hardwarenames", true, hardwareNamesItem, settings);
            _hardwareNames.Changed += delegate
            {
                Resize();
            };

            UserOption alwaysOnTop = new UserOption("sensorGadget.AlwaysOnTop", false, alwaysOnTopItem, settings);

            alwaysOnTop.Changed += delegate
            {
                AlwaysOnTop = alwaysOnTop.Value;
            };
            UserOption lockPositionAndSize = new UserOption("sensorGadget.LockPositionAndSize", false, lockItem, settings);

            lockPositionAndSize.Changed += delegate
            {
                LockPositionAndSize = lockPositionAndSize.Value;
            };

            HitTest += delegate(object sender, HitTestEventArgs e)
            {
                if (lockPositionAndSize.Value)
                {
                    return;
                }

                if (e.Location.X < LeftBorder)
                {
                    e.HitResult = HitResult.Left;
                    return;
                }
                if (e.Location.X > Size.Width - 1 - RightBorder)
                {
                    e.HitResult = HitResult.Right;
                }
            };

            SizeChanged += delegate
            {
                settings.SetValue("sensorGadget.Width", Size.Width);
                Redraw();
            };

            VisibleChanged += delegate
            {
                Rectangle bounds       = new Rectangle(Location, Size);
                Screen    screen       = Screen.FromRectangle(bounds);
                Rectangle intersection = Rectangle.Intersect(screen.WorkingArea, bounds);
                if (intersection.Width < Math.Min(16, bounds.Width) || intersection.Height < Math.Min(16, bounds.Height))
                {
                    Location = new Point(screen.WorkingArea.Width / 2 - bounds.Width / 2, screen.WorkingArea.Height / 2 - bounds.Height / 2);
                }
            };

            MouseDoubleClick += delegate
            {
                SendHideShowCommand();
            };
        }