How do I disable the c# message box beep?

后端 未结 7 1048
攒了一身酷
攒了一身酷 2020-12-16 13:30

Whenever trigger a messagebox used in my C# program I get a very annoying beep from my computer. How do I disable this beep using C# code.

The code I am using is ve

7条回答
  •  情话喂你
    2020-12-16 14:06

    Here's how I solved that little problem.

    Add this simple class to your project. It's part of my personal library now but you can add the class directly in your project

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Runtime.InteropServices;
    
    namespace MyCSharpLibrary
    {
        public class Volume
        {
            [DllImport("winmm.dll")]
            public static extern int waveOutGetVolume(IntPtr h, out uint dwVolume);
    
            [DllImport("winmm.dll")]
            public static extern int waveOutSetVolume(IntPtr h, uint dwVolume);
    
            private static uint _savedVolumeLevel;
            private static Boolean VolumeLevelSaved = false;
    
            // ----------------------------------------------------------------------------
            public static void On()
            {
                if (VolumeLevelSaved)
                {
                    waveOutSetVolume(IntPtr.Zero, _savedVolumeLevel);
                }
            }
    
            // ----------------------------------------------------------------------------
            public static void Off()
            {
                waveOutGetVolume(IntPtr.Zero, out _savedVolumeLevel);
                VolumeLevelSaved = true;
    
                waveOutSetVolume(IntPtr.Zero, 0);
            }
        }
    }
    

    Now call Volume.Off() before calling MessageBox and Volume.On() after

    Volume.Off();
    MessageBox.Show("\n Information \n", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
    Volume.On();
    

    I prefer that approach because I don't have to make modifications to Windows and I can select any icons I want for my MessageBoxes.

    Thank you, bye

提交回复
热议问题