简体   繁体   中英

How to persist the selection of an item in a combo box between application restarts

In a WinForms application I am showing a list of all available audio devices in a combo box. I want the user to be able to select one of these items and for that selection to be persisted so that the next time the application is loaded the same device from combo box will selected by default.

How can I solve this?

Code to get list of available audio devices:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp2
{
    public partial class Form2 : Form
    {
        [DllImport("winmm.dll", SetLastError = true)]
        static extern uint waveInGetNumDevs();

        [DllImport("winmm.dll", SetLastError = true, CharSet = CharSet.Auto)]
        public static extern uint waveInGetDevCaps(uint hwo, ref WAVEOUTCAPS pwoc, uint cbwoc);

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        public struct WAVEOUTCAPS
        {
            public ushort wMid;
            public ushort wPid;
            public uint vDriverVersion;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)]
            public string szPname;
            public uint dwFormats;
            public ushort wChannels;
            public ushort wReserved1;
            public uint dwSupport;
        }

        public void FillSoundDevicesInCombobox()
        {
            uint devices = waveInGetNumDevs();
            WAVEOUTCAPS caps = new WAVEOUTCAPS();
            for (uint i = 0; i < devices; i++)
            {
                waveInGetDevCaps(i, ref caps, (uint)Marshal.SizeOf(caps));
                CB1.Items.Add(caps.szPname);
            }

        }
        public Form2()
        {
            InitializeComponent();
        }

        private void Form2_Load(object sender, EventArgs e)
        {
            FillSoundDevicesInCombobox();

        }

private void button1_Click(object sender, EventArgs e)
        {
           
    }
    }
}

My expectation is that when the user clicks on the button the selected item will be saved. Then if I restart the application, the same device should be re-selected when the form loads.

I'll ignore the microphone issue and instead address the real underlying issue:

How to persist the selection of an item in a combo box between application restarts

The easiest way to do this in a WinForms application is to use the Application Settings:

Application Settings for Windows Forms
The Applications Settings feature of Windows Forms makes it easy to create, store, and maintain custom application and user preferences on the client. With Application Settings, you can store not only application data such as database connection strings, but also user-specific data, such as toolbar positions and most-recently used lists.

For your scenario, we want to focus on User scoped settings as these can be edited at runtime and persited back to file so the changes can be read at application startup.

How To: Create a new setting at design time
You can create a new setting at design time by using the Settings designer in Visual Studio. The Settings designer is a grid-style interface that allows you to create new settings and specify properties for those settings. You must specify Name, Value, Type and Scope for your new settings. Once a setting is created, it is accessible in code.

在设计时创建设置

Once your setting has been defined we can use it in the code. In this scenario I am NOT storing the index, instead I will use the actual value. This was if in a future execution the values loaded for the microphones is different or in a different sequence, the code will still select the correct microphone, or none at all.

We can access the Application Settings through the Properties.Settings.Default namespace:

private void Form2_Load(object sender, EventArgs e)
{
    FillSoundDevicesInCombobox();

    // Only select the device if there is a value to load
    if (!String.IsNullOrWhiteSpace(Properties.Settings.Default.SelectedAudioDevice))
    {
        // find the device, matching on the value, not index
        var item = CB1.Items.Cast<string>().FirstOrDefault(x => x.Equals(Properties.Settings.Default.SelectedAudioDevice));
        // only select the device if we found one that matched the previous selection.
        if (item != null)
            CB1.SelectedItem = item;
    }
}

Then in the button click, we can store the current selection:

How To: Write User Settings at Run Time with C#
Settings that are application-scoped are read-only, and can only be changed at design time or by altering the.config file in between application sessions. Settings that are user-scoped, however, can be written at run time just as you would change any property value. The new value persists for the duration of the application session. You can persist the changes to the settings between application sessions by calling the Save method.

private void button1_Click(object sender, EventArgs e)
{
    // persist the changes to the user scoped settings store
    Properties.Settings.Default.SelectedAudioDevice = CB1.SelectedItem?.ToString();
    Properties.Settings.Default.Save();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM