patterncsharpMinor
TrackBar volume control
Viewed 0 times
trackbarcontrolvolume
Problem
This changes the application's volume through the Trackbar (1-100, 1% to 100%):
Is it possible to make
For example:
There, I would like to use it on everything, as they all work pretty much the same. But if I have to write
Is this code okay, or can it be improved?
public static class NativeMethods
{
//Winm WindowsSound
[DllImport("winmm.dll")]
internal static extern int waveOutGetVolume(IntPtr hwo, out uint dwVolume);
[DllImport("winmm.dll")]
internal static extern int waveOutSetVolume(IntPtr hwo, uint dwVolume);
}
private void trackBar1_Scroll(object sender, EventArgs e)
{
uint CurrVol = ushort.MaxValue / 2;
NativeMethods.waveOutGetVolume(IntPtr.Zero, out CurrVol);
ushort CalcVol = (ushort)(CurrVol & 0x0000ffff);
int NewVolume = ((ushort.MaxValue / 100) * trackBar1.Value);
uint NewVolumeAllChannels = (((uint)NewVolume & 0x0000ffff) | ((uint)NewVolume << 16));
NativeMethods.waveOutSetVolume(IntPtr.Zero, NewVolumeAllChannels);
label1.Text = Convert.ToString("Volume: " + trackBar1.Value + "%");
}Is it possible to make
String.Format use multiple arguments/values?For example:
String Status = String.Format("Current Buffer: {0}", waveProvider.BufferedDuration.Milliseconds, TimesBufferClear) + " Clear: " + TimesBufferClear.ToString() + " Ping: " + PingReply + " Buffer: " + SendStream.BufferMilliseconds;There, I would like to use it on everything, as they all work pretty much the same. But if I have to write
String.Format every time, it will take up much more space.Is this code okay, or can it be improved?
Solution
There isn't much to review in 6 lines of code. But oh well.
-
- Native methods return error codes, so it is good practice to handle those codes somehow, not just ignore them. For example, if method reports, that there is no sound driver or no sound card or w/e, it makes sense to notify user somehow. Write warning in the status bar of your window or something.
- It is meaningless to initialize
CurrVol, since its value will be overriden anyway, wont it? And, if its your real code, you dont have to recieve current volume in order to set it to begin with.
-
Convert.ToString should be refactored to String.Format("Volume: {0}%", trackBar1.Value);. More complex example:var status = String.Format("Current Buffer: {0} Clear: {1} Ping: {2} Buffer: {3}", waveProvider.BufferedDuration.Milliseconds, TimesBufferClear, PingReply, SendStream.BufferMilliseconds);Code Snippets
var status = String.Format("Current Buffer: {0} Clear: {1} Ping: {2} Buffer: {3}", waveProvider.BufferedDuration.Milliseconds, TimesBufferClear, PingReply, SendStream.BufferMilliseconds);Context
StackExchange Code Review Q#30413, answer score: 4
Revisions (0)
No revisions yet.