ant2009
ant2009

Reputation: 22486

C# Detecting sound card

C# 2008

I am using the code below to find out if the user has a sound card install or not. I have found 2 methods and wondering if one is better than the other. Is there anything better than the ones I have posted?

I am detecting on a windows desktop that this running XP, Vista, and Seven.

Many thanks for any advice,

public partial class Form1 : Form
{
    [DllImport("winmm.dll", SetLastError = true)]
    public static extern uint waveOutGetNumDevs();

    public Form1()
    {
        InitializeComponent();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        if (waveOutGetNumDevs() != 0)
        {
            Console.WriteLine("The sound card is detected");
        }
        else
        {
            Console.WriteLine("No sound card");
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        ManagementObjectSearcher searcher = 
            new ManagementObjectSearcher("Select ProductName from Win32_SoundDevice");

        foreach (ManagementObject device in searcher.Get())
        {
            Console.WriteLine("Sound card {0}", 
                device.GetPropertyValue("ProductName"));

        }


    }
}

Upvotes: 1

Views: 2854

Answers (1)

BenAlabaster
BenAlabaster

Reputation: 39816

I personally prefer WMI (your second solution) to referencing the Win32 API through p/Invoke (your first solution)... I think this is likely to be a matter of preference though. The Win32 API is there to be used, and obviously has a potential native performance advantage over WMI. That said, WMI was provided for exactly this type of purpose so why not use it?

Both have their advantages and disadvantages, though WMI is more intuitive and far more flexible than the Win32 API, you can query it with a relatively comprehensive query language, it's simple to maintain, it's easy to read, it does the job it was intended for well and that is communicate with the operating system configuration which is exactly what you're trying to do.

Therefore my conclusion is (in my opinion) that WMI is the way to go. Like I said though, this is just my opinion and is somewhat subjective.

Upvotes: 1

Related Questions