|
_Damian S_ wrote: Use a label for your control instead of a text box
How could i use a label control instead of the text box? because when i drag this numeric up down control on the form, it already display a textbox with an arrow key.
|
|
|
|
|
Ah... I thought you were writing your own custom control using a text box and two buttons...
-------------------------------------------
Don't walk in front of me, I may not follow;
Don't walk behind me, I may not lead;
Just bugger off and leave me alone!!
|
|
|
|
|
No, I didn't develop my own control. This control is the built in control in vb2005. Do you have any other idea to the question that I asked in the previous message?
|
|
|
|
|
There's no way to do it in the stock control. You'd have to "roll your own" to get this kind of functionality.
|
|
|
|
|
I have been given the following spec.
Task: Create a Database access class for your project. This class represents middle tier (business logic) that access a database.
Deliverable:
* Create a method that returns a datareader. This method should take a SQL statement (select * from person). The method itself should do everything else. Return the datareader. You can instantiate this class and assign it to the datasource just before the data bind like this:
dg1.datasource=myDBClass.getDataReader("Select * from person")
* Create a method that returns a dataset. Remember that the dataset can hold multiple tables. So for this method you should be able to either pass it an array of select statements or be able to call the method more than once. In either case, you will need a SQL statement, the dataset you want to populate, and what you want to call the table in the dataset.
* Create a method that returns a true or false after attempt to before an update, insert, or delete. Each of these items do not return a resultset; therefore, use a try/catch block to see if it completes.
I have only been programming in vb for about 2 1/2 weeks, so this has me riddled. Can someone help, or at least point me in the right direction. Are there any examples on Code Project?
Thanks,
|
|
|
|
|
ddtayl06 wrote: I have only been programming in vb for about 2 1/2 weeks
Pretty advanced task requirement for someone with only 2 1/2 weeks programming experience. Homework project, I suspect?
"Try asking what you want to know, rather than asking a question whose answer you know." - Christian Graus
|
|
|
|
|
This doesn't pass the "sniff test" for homework. 2.5 weeks of "class" and you've been given this assignment?? I don't think so.
Though this is very easy to put together, given a short breakdown of the problem.
You're writing a Method that returns a DataReader. This method will take an SQL statement as a String argument.
You're writing another method that takes three arguments, an SQL statement, a DataSet, and a name for a table in that DataSet.
The first sentance in the third point makes no sense.
|
|
|
|
|
I've created and compliled an assembly from a text string using vbcodeprovider and am able to get the results back from it. But I'm missing something critical -- how do I pass data from my running program to that assembly? I'd like to pass for instance a couple of arrays that the code in the assembly will modify.
Thanks as always!
|
|
|
|
|
Oh, sorry, I think you have to compile the assembly and then run it, passing the parameter(s) to it on the run.
|
|
|
|
|
I used an online translator to translate some c# code to vb.net. Anyways all of my events for my main form seem to be giving me this error.
Handles clause requires a WithEvents variable defined in the containing type or one of its base types.
Here's one example of part of the code with the problem:
Private Sub buttonSoundfile_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles buttonSoundfile.Click<br />
OnCreateSoundFile()<br />
End Sub
If anybody has an idea what could be causing this it would be a big help. I will post the complete code for the form in the next message just incase that helps.
|
|
|
|
|
'---------------------------------------------------------------------------- <br />
' File: Main.cs <br />
' <br />
' Copyright (c) Microsoft Corp. All rights reserved. <br />
'----------------------------------------------------------------------------- <br />
Imports System<br />
Imports System.IO<br />
Imports System.Drawing<br />
Imports System.Windows.Forms<br />
Imports System.Threading<br />
Imports Microsoft.DirectX<br />
Imports Microsoft.DirectX.DirectSound<br />
<br />
Public Class MainForm<br />
Inherits Form<br />
Private labelMainInputformatText As Label<br />
Private checkboxRecord As CheckBox<br />
Private buttonSoundfile As Button<br />
Private labelFilename As Label<br />
Private labelStatic As Label<br />
<br />
Public PositionNotify As BufferPositionNotify() = New BufferPositionNotify(NumberRecordNotifications) {}<br />
Public Const NumberRecordNotifications As Integer = 16<br />
Public NotificationEvent As AutoResetEvent = Nothing<br />
Public applicationBuffer As CaptureBuffer = Nothing<br />
Public CaptureDeviceGuid As Guid = Guid.Empty<br />
Public applicationDevice As Capture = Nothing<br />
Private FileName As String = String.Empty<br />
Public applicationNotify As Notify = Nothing<br />
Private NotifyThread As Thread = Nothing<br />
Private WaveFile As FileStream = Nothing<br />
Private Writer As BinaryWriter = Nothing<br />
Private Path As String = String.Empty<br />
Public CaptureBufferSize As Integer = 0<br />
Public NextCaptureOffset As Integer = 0<br />
Private Recording As Boolean = False<br />
Public InputFormat As WaveFormat<br />
Private SampleCount As Integer = 0<br />
Public NotifySize As Integer = 0<br />
Private Capturing As Boolean = False<br />
<br />
<STAThread()> _<br />
Public Shared Sub Main()<br />
Try<br />
Using form As New MainForm()<br />
form.ShowDialog()<br />
End Using<br />
Catch<br />
End Try<br />
End Sub<br />
<br />
Private Sub MainForm_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing<br />
If NotificationEvent IsNot Nothing Then<br />
Capturing = False<br />
NotificationEvent.[Set]()<br />
End If<br />
If applicationBuffer IsNot Nothing Then<br />
If applicationBuffer.Capturing Then<br />
StartOrStopRecord(False)<br />
End If<br />
End If<br />
End Sub<br />
<br />
Public Sub New()<br />
' <br />
' Required for Windows Form Designer support <br />
' <br />
InitializeComponent()<br />
<br />
Dim devices As New DevicesForm(Me)<br />
devices.ShowDialog(Me)<br />
InitDirectSound()<br />
If applicationDevice Is Nothing Then<br />
Close()<br />
Else<br />
Dim formats As New FormatsForm(Me)<br />
If formats.ShowDialog(Me) = DialogResult.OK Then<br />
<br />
labelMainInputformatText.Text = String.Format("{0} Hz, {1}-bit ", InputFormat.SamplesPerSecond, InputFormat.BitsPerSample) + (IIf((1 = InputFormat.Channels), "Mono", "Stereo"))<br />
<br />
CreateCaptureBuffer()<br />
Else<br />
Me.Close()<br />
End If<br />
End If<br />
End Sub<br />
#Region "InitializeComponent code"<br />
Private Sub InitializeComponent()<br />
Me.labelStatic = New System.Windows.Forms.Label<br />
Me.labelMainInputformatText = New System.Windows.Forms.Label<br />
Me.checkboxRecord = New System.Windows.Forms.CheckBox<br />
Me.buttonSoundfile = New System.Windows.Forms.Button<br />
Me.labelFilename = New System.Windows.Forms.Label<br />
Me.SuspendLayout()<br />
'<br />
'labelStatic<br />
'<br />
Me.labelStatic.Location = New System.Drawing.Point(10, 46)<br />
Me.labelStatic.Name = "labelStatic"<br />
Me.labelStatic.Size = New System.Drawing.Size(75, 13)<br />
Me.labelStatic.TabIndex = 0<br />
Me.labelStatic.Text = "Input Format:"<br />
'<br />
'labelMainInputformatText<br />
'<br />
Me.labelMainInputformatText.Location = New System.Drawing.Point(90, 46)<br />
Me.labelMainInputformatText.Name = "labelMainInputformatText"<br />
Me.labelMainInputformatText.Size = New System.Drawing.Size(262, 13)<br />
Me.labelMainInputformatText.TabIndex = 1<br />
'<br />
'checkboxRecord<br />
'<br />
Me.checkboxRecord.Appearance = System.Windows.Forms.Appearance.Button<br />
Me.checkboxRecord.Enabled = False<br />
Me.checkboxRecord.FlatStyle = System.Windows.Forms.FlatStyle.System<br />
Me.checkboxRecord.Location = New System.Drawing.Point(369, 40)<br />
Me.checkboxRecord.Name = "checkboxRecord"<br />
Me.checkboxRecord.Size = New System.Drawing.Size(75, 23)<br />
Me.checkboxRecord.TabIndex = 2<br />
Me.checkboxRecord.Text = "&Record"<br />
'<br />
'buttonSoundfile<br />
'<br />
Me.buttonSoundfile.Location = New System.Drawing.Point(10, 11)<br />
Me.buttonSoundfile.Name = "buttonSoundfile"<br />
Me.buttonSoundfile.Size = New System.Drawing.Size(78, 21)<br />
Me.buttonSoundfile.TabIndex = 3<br />
Me.buttonSoundfile.Text = "Sound &file..."<br />
'<br />
'labelFilename<br />
'<br />
Me.labelFilename.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D<br />
Me.labelFilename.Location = New System.Drawing.Point(96, 11)<br />
Me.labelFilename.Name = "labelFilename"<br />
Me.labelFilename.Size = New System.Drawing.Size(348, 21)<br />
Me.labelFilename.TabIndex = 4<br />
Me.labelFilename.Text = "No file loaded."<br />
Me.labelFilename.TextAlign = System.Drawing.ContentAlignment.MiddleLeft<br />
'<br />
'MainForm<br />
'<br />
Me.AcceptButton = Me.buttonSoundfile<br />
Me.ClientSize = New System.Drawing.Size(454, 77)<br />
Me.Controls.Add(Me.labelStatic)<br />
Me.Controls.Add(Me.labelMainInputformatText)<br />
Me.Controls.Add(Me.checkboxRecord)<br />
Me.Controls.Add(Me.buttonSoundfile)<br />
Me.Controls.Add(Me.labelFilename)<br />
Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog<br />
Me.Name = "MainForm"<br />
Me.Text = "CaptureSound3"<br />
Me.ResumeLayout(False)<br />
<br />
End Sub<br />
#End Region<br />
Private Sub InitDirectSound()<br />
CaptureBufferSize = 0<br />
NotifySize = 0<br />
<br />
' Create DirectSound.Capture using the preferred capture device <br />
Try<br />
applicationDevice = New Capture(CaptureDeviceGuid)<br />
Catch<br />
End Try<br />
End Sub<br />
Private Sub CreateCaptureBuffer()<br />
'----------------------------------------------------------------------------- <br />
' Name: CreateCaptureBuffer() <br />
' Desc: Creates a capture buffer and sets the format <br />
'----------------------------------------------------------------------------- <br />
Dim dscheckboxd As New CaptureBufferDescription()<br />
<br />
If applicationNotify IsNot Nothing Then<br />
applicationNotify.Dispose()<br />
applicationNotify = Nothing<br />
End If<br />
If applicationBuffer IsNot Nothing Then<br />
applicationBuffer.Dispose()<br />
applicationBuffer = Nothing<br />
End If<br />
<br />
If 0 = InputFormat.Channels Then<br />
Return<br />
End If<br />
<br />
' Set the notification size <br />
NotifySize = IIf((1024 > InputFormat.AverageBytesPerSecond / 8), 1024, (InputFormat.AverageBytesPerSecond / 8))<br />
NotifySize -= NotifySize Mod InputFormat.BlockAlign<br />
<br />
' Set the buffer sizes <br />
CaptureBufferSize = NotifySize * NumberRecordNotifications<br />
<br />
' Create the capture buffer <br />
dscheckboxd.BufferBytes = CaptureBufferSize<br />
InputFormat.FormatTag = WaveFormatTag.Pcm<br />
dscheckboxd.Format = InputFormat<br />
' Set the format during creatation <br />
applicationBuffer = New CaptureBuffer(dscheckboxd, applicationDevice)<br />
NextCaptureOffset = 0<br />
<br />
InitNotifications()<br />
End Sub<br />
Private Sub InitNotifications()<br />
'----------------------------------------------------------------------------- <br />
' Name: InitNotifications() <br />
' Desc: Inits the notifications on the capture buffer which are handled <br />
' in the notify thread. <br />
'----------------------------------------------------------------------------- <br />
<br />
If applicationBuffer Is Nothing Then<br />
Throw New NullReferenceException()<br />
End If<br />
<br />
' Create a thread to monitor the notify events <br />
If NotifyThread Is Nothing Then<br />
NotifyThread = New Thread(New ThreadStart(AddressOf WaitThread))<br />
Capturing = True<br />
NotifyThread.Start()<br />
<br />
' Create a notification event, for when the sound stops playing <br />
NotificationEvent = New AutoResetEvent(False)<br />
End If<br />
For i As Integer = 0 To NumberRecordNotifications - 1<br />
<br />
<br />
' Setup the notification positions <br />
PositionNotify(i).Offset = (NotifySize * i) + NotifySize - 1<br />
PositionNotify(i).EventNotifyHandle = NotificationEvent.Handle<br />
Next<br />
<br />
applicationNotify = New Notify(applicationBuffer)<br />
<br />
' Tell DirectSound when to notify the app. The notification will come in the from <br />
' of signaled events that are handled in the notify thread. <br />
applicationNotify.SetNotificationPositions(PositionNotify, NumberRecordNotifications)<br />
End Sub<br />
<br />
Private Sub checkboxRecord_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles checkboxRecord.CheckedChanged<br />
Recording = Not Recording<br />
StartOrStopRecord(Recording)<br />
<br />
If Not Recording Then<br />
checkboxRecord.Enabled = False<br />
End If<br />
End Sub<br />
<br />
Private Sub StartOrStopRecord(ByVal StartRecording As Boolean)<br />
'----------------------------------------------------------------------------- <br />
' Name: StartOrStopRecord() <br />
' Desc: Starts or stops the capture buffer from recording <br />
'----------------------------------------------------------------------------- <br />
<br />
If StartRecording Then<br />
' Create a capture buffer, and tell the capture <br />
' buffer to start recording <br />
CreateCaptureBuffer()<br />
applicationBuffer.Start(True)<br />
Else<br />
' Stop the buffer, and read any data that was not <br />
' caught by a notification <br />
applicationBuffer.[Stop]()<br />
<br />
RecordCapturedData()<br />
<br />
Writer.Seek(4, SeekOrigin.Begin)<br />
' Seek to the length descriptor of the RIFF file. <br />
Writer.Write(CInt((SampleCount + 36)))<br />
' Write the file length, minus first 8 bytes of RIFF description. <br />
Writer.Seek(40, SeekOrigin.Begin)<br />
' Seek to the data length descriptor of the RIFF file. <br />
Writer.Write(SampleCount)<br />
' Write the length of the sample data in bytes. <br />
Writer.Close()<br />
' Close the file now. <br />
Writer = Nothing<br />
' Set the writer to null. <br />
' Set the FileStream to null. <br />
WaveFile = Nothing<br />
End If<br />
End Sub<br />
<br />
Private Sub CreateRIFF()<br />
'************************************************************************* <br />
' <br />
' Here is where the file will be created. A <br />
' wave file is a RIFF file, which has chunks <br />
' of data that describe what the file contains. <br />
' A wave RIFF file is put together like this: <br />
' <br />
' The 12 byte RIFF chunk is constructed like this: <br />
' Bytes 0 - 3 : 'R' 'I' 'F' 'F' <br />
' Bytes 4 - 7 : Length of file, minus the first 8 bytes of the RIFF description. <br />
' (4 bytes for "WAVE" + 24 bytes for format chunk length + <br />
' 8 bytes for data chunk description + actual sample data size.) <br />
' Bytes 8 - 11: 'W' 'A' 'V' 'E' <br />
' <br />
' The 24 byte FORMAT chunk is constructed like this: <br />
' Bytes 0 - 3 : 'f' 'm' 't' ' ' <br />
' Bytes 4 - 7 : The format chunk length. This is always 16. <br />
' Bytes 8 - 9 : File padding. Always 1. <br />
' Bytes 10- 11: Number of channels. Either 1 for mono, or 2 for stereo. <br />
' Bytes 12- 15: Sample rate. <br />
' Bytes 16- 19: Number of bytes per second. <br />
' Bytes 20- 21: Bytes per sample. 1 for 8 bit mono, 2 for 8 bit stereo or <br />
' 16 bit mono, 4 for 16 bit stereo. <br />
' Bytes 22- 23: Number of bits per sample. <br />
' <br />
' The DATA chunk is constructed like this: <br />
' Bytes 0 - 3 : 'd' 'a' 't' 'a' <br />
' Bytes 4 - 7 : Length of data, in bytes. <br />
' Bytes 8 -...: Actual sample data. <br />
' <br />
' ************************************************************************** <br />
<br />
<br />
' Open up the wave file for writing. <br />
WaveFile = New FileStream(FileName, FileMode.Create)<br />
Writer = New BinaryWriter(WaveFile)<br />
<br />
' Set up file with RIFF chunk info. <br />
Dim ChunkRiff As Char() = {"R"c, "I"c, "F"c, "F"c}<br />
Dim ChunkType As Char() = {"W"c, "A"c, "V"c, "E"c}<br />
Dim ChunkFmt As Char() = {"f"c, "m"c, "t"c, " "c}<br />
Dim ChunkData As Char() = {"d"c, "a"c, "t"c, "a"c}<br />
<br />
Dim shPad As Short = 1<br />
' File padding <br />
Dim nFormatChunkLength As Integer = 16<br />
' Format chunk length. <br />
Dim nLength As Integer = 0<br />
' File length, minus first 8 bytes of RIFF description. This will be filled in later. <br />
Dim shBytesPerSample As Short = 0<br />
' Bytes per sample. <br />
' Figure out how many bytes there will be per sample. <br />
If 8 = InputFormat.BitsPerSample AndAlso 1 = InputFormat.Channels Then<br />
shBytesPerSample = 1<br />
ElseIf (8 = InputFormat.BitsPerSample AndAlso 2 = InputFormat.Channels) OrElse (16 = InputFormat.BitsPerSample AndAlso 1 = InputFormat.Channels) Then<br />
shBytesPerSample = 2<br />
ElseIf 16 = InputFormat.BitsPerSample AndAlso 2 = InputFormat.Channels Then<br />
shBytesPerSample = 4<br />
End If<br />
<br />
' Fill in the riff info for the wave file. <br />
Writer.Write(ChunkRiff)<br />
Writer.Write(nLength)<br />
Writer.Write(ChunkType)<br />
<br />
' Fill in the format info for the wave file. <br />
Writer.Write(ChunkFmt)<br />
Writer.Write(nFormatChunkLength)<br />
Writer.Write(shPad)<br />
Writer.Write(InputFormat.Channels)<br />
Writer.Write(InputFormat.SamplesPerSecond)<br />
Writer.Write(InputFormat.AverageBytesPerSecond)<br />
Writer.Write(shBytesPerSample)<br />
Writer.Write(InputFormat.BitsPerSample)<br />
<br />
' Now fill in the data chunk. <br />
Writer.Write(ChunkData)<br />
Writer.Write(CInt(0))<br />
' The sample length will be written in later. <br />
End Sub<br />
<br />
Private Sub RecordCapturedData()<br />
'----------------------------------------------------------------------------- <br />
' Name: RecordCapturedData() <br />
' Desc: Copies data from the capture buffer to the output buffer <br />
'----------------------------------------------------------------------------- <br />
Dim CaptureData As Byte() = Nothing<br />
Dim ReadPos As Integer<br />
Dim CapturePos As Integer<br />
Dim LockSize As Integer<br />
<br />
applicationBuffer.GetCurrentPosition(CapturePos, ReadPos)<br />
LockSize = ReadPos - NextCaptureOffset<br />
If LockSize < 0 Then<br />
LockSize += CaptureBufferSize<br />
End If<br />
<br />
' Block align lock size so that we are always write on a boundary <br />
LockSize -= (LockSize Mod NotifySize)<br />
<br />
If 0 = LockSize Then<br />
Return<br />
End If<br />
<br />
' Read the capture buffer. <br />
CaptureData = applicationBuffer.Read(NextCaptureOffset, GetType(Byte), LockFlag.None, LockSize) 'CByte()<br />
<br />
' Write the data into the wav file <br />
Writer.Write(CaptureData, 0, CaptureData.Length)<br />
<br />
' Update the number of samples, in bytes, of the file so far. <br />
SampleCount += CaptureData.Length<br />
<br />
' Move the capture offset along <br />
NextCaptureOffset += CaptureData.Length<br />
NextCaptureOffset = NextCaptureOffset Mod CaptureBufferSize<br />
' Circular buffer <br />
End Sub<br />
<br />
Private Sub buttonSoundfile_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles buttonSoundfile.Click<br />
OnCreateSoundFile()<br />
End Sub<br />
<br />
Private Sub OnCreateSoundFile()<br />
'----------------------------------------------------------------------------- <br />
' Name: OnCreateSoundFile() <br />
' Desc: Called when the user requests to save to a sound file <br />
'----------------------------------------------------------------------------- <br />
<br />
Dim ofd As New SaveFileDialog()<br />
Dim wf As New WaveFormat()<br />
Dim result As DialogResult<br />
<br />
' Get the default media path (something like C:\WINDOWS\MEDIA) <br />
If String.Empty = Path Then<br />
Path = Environment.SystemDirectory.Substring(0, Environment.SystemDirectory.LastIndexOf("\")) + "\media"<br />
End If<br />
<br />
If Recording Then<br />
' Stop the capture and read any data that <br />
' was not caught by a notification <br />
StartOrStopRecord(False)<br />
Recording = False<br />
End If<br />
<br />
ofd.DefaultExt = ".wav"<br />
ofd.Filter = "Wave Files|*.wav|All Files|*.*"<br />
ofd.FileName = FileName<br />
ofd.InitialDirectory = Path<br />
<br />
' Update the UI controls to show the sound as loading a file <br />
checkboxRecord.Enabled = False<br />
labelFilename.Text = "Saving file..."<br />
<br />
' Display the OpenFileName dialog. Then, try to load the specified file <br />
result = ofd.ShowDialog(Me)<br />
<br />
If DialogResult.Abort = result OrElse DialogResult.Cancel = result Then<br />
labelFilename.Text = "Save aborted."<br />
Return<br />
End If<br />
FileName = ofd.FileName<br />
<br />
Try<br />
CreateRIFF()<br />
Catch<br />
labelFilename.Text = "Could not create wave file."<br />
Return<br />
End Try<br />
<br />
' Update the UI controls to show the sound as the file is loaded <br />
labelFilename.Text = FileName<br />
checkboxRecord.Enabled = True<br />
<br />
' Remember the path for next time <br />
Path = FileName.Substring(0, FileName.LastIndexOf("\"))<br />
End Sub<br />
<br />
Private Sub WaitThread()<br />
While Capturing<br />
'Sit here and wait for a message to arrive <br />
NotificationEvent.WaitOne(Timeout.Infinite, True)<br />
RecordCapturedData()<br />
End While<br />
End Sub<br />
<br />
Private Sub labelMainInputformatText_Click(ByVal sender As Object, ByVal e As EventArgs) Handles labelMainInputformatText.Click<br />
<br />
End Sub<br />
<br />
Private Sub labelFilename_Click(ByVal sender As Object, ByVal e As EventArgs) Handles labelFilename.Click<br />
<br />
End Sub<br />
<br />
Private Sub labelStatic_Click(ByVal sender As Object, ByVal e As EventArgs) Handles labelStatic.Click<br />
<br />
End Sub<br />
<br />
End Class
|
|
|
|
|
Post the original C# code and I'll convert it for you.
Right off the bat (and corresponding to the error), you need "WithEvents" on the declaration of buttonSoundfile:
e.g.,
Private WithEvents buttonSoundfile As ...
David Anton
http://www.tangiblesoftwaresolutions.com
Instant C#: VB to C# converter
Instant VB: C# to VB converter
C++ to C# Converter: converts C++ to C#
C++ to VB Converter: converts C++ to VB
C++ to Java Converter: converts C++ to Java
Instant C++: converts C# to C++/CLI and VB to C++/CLI
|
|
|
|
|
I appreciate your offer to help. There's actually 3 forms with code (no modules or other classes) I'll post them all below. I just showed the main form in the example.
I'd like to understand what withevents is and what's going wrong here though if you could explain.
Thank you very much for your help.
Mike
|
|
|
|
|
//----------------------------------------------------------------------------
// File: Main.cs
//
// Copyright (c) Microsoft Corp. All rights reserved.
//-----------------------------------------------------------------------------
using System;
using System.IO;
using System.Drawing;
using System.Windows.Forms;
using System.Threading;
using Microsoft.DirectX;
using Microsoft.DirectX.DirectSound;
public class MainForm : Form
{
private Label labelMainInputformatText;
private CheckBox checkboxRecord;
private Button buttonSoundfile;
private Label labelFilename;
private Label labelStatic;
public BufferPositionNotify[] PositionNotify = new BufferPositionNotify[NumberRecordNotifications + 1];
public const int NumberRecordNotifications = 16;
public AutoResetEvent NotificationEvent = null;
public CaptureBuffer applicationBuffer = null;
public Guid CaptureDeviceGuid = Guid.Empty;
public Capture applicationDevice = null;
private string FileName = string.Empty;
public Notify applicationNotify = null;
private Thread NotifyThread = null;
private FileStream WaveFile = null;
private BinaryWriter Writer = null;
private string Path = string.Empty;
public int CaptureBufferSize = 0;
public int NextCaptureOffset = 0;
private bool Recording = false;
public WaveFormat InputFormat;
private int SampleCount = 0;
public int NotifySize = 0;
private bool Capturing = false;
[STAThread]
public static void Main()
{
try
{
using(MainForm form = new MainForm())
{
form.ShowDialog();
}
}
catch{}
}
private void MainForm_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if (null != NotificationEvent)
{
Capturing = false;
NotificationEvent.Set();
}
if (null != applicationBuffer)
if (applicationBuffer.Capturing)
StartOrStopRecord(false);
}
public MainForm()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
DevicesForm devices = new DevicesForm(this);
devices.ShowDialog(this);
InitDirectSound();
if (null == applicationDevice)
Close();
else
{
FormatsForm formats = new FormatsForm(this);
if (formats.ShowDialog(this) == DialogResult.OK)
{
labelMainInputformatText.Text = string.Format("{0} Hz, {1}-bit ",
InputFormat.SamplesPerSecond,
InputFormat.BitsPerSample) +
((1 == InputFormat.Channels) ? "Mono" : "Stereo");
CreateCaptureBuffer();
}
else
{
this.Close();
}
}
}
#region InitializeComponent code
private void InitializeComponent()
{
this.labelStatic = new System.Windows.Forms.Label();
this.labelMainInputformatText = new System.Windows.Forms.Label();
this.checkboxRecord = new System.Windows.Forms.CheckBox();
this.buttonSoundfile = new System.Windows.Forms.Button();
this.labelFilename = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// labelStatic
//
this.labelStatic.Location = new System.Drawing.Point(10, 46);
this.labelStatic.Name = "labelStatic";
this.labelStatic.Size = new System.Drawing.Size(75, 13);
this.labelStatic.TabIndex = 0;
this.labelStatic.Text = "Input Format:";
this.labelStatic.Click += new System.EventHandler(this.labelStatic_Click);
//
// labelMainInputformatText
//
this.labelMainInputformatText.Location = new System.Drawing.Point(90, 46);
this.labelMainInputformatText.Name = "labelMainInputformatText";
this.labelMainInputformatText.Size = new System.Drawing.Size(262, 13);
this.labelMainInputformatText.TabIndex = 1;
this.labelMainInputformatText.Click += new System.EventHandler(this.labelMainInputformatText_Click);
//
// checkboxRecord
//
this.checkboxRecord.Appearance = System.Windows.Forms.Appearance.Button;
this.checkboxRecord.Enabled = false;
this.checkboxRecord.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.checkboxRecord.Location = new System.Drawing.Point(369, 40);
this.checkboxRecord.Name = "checkboxRecord";
this.checkboxRecord.Size = new System.Drawing.Size(75, 23);
this.checkboxRecord.TabIndex = 2;
this.checkboxRecord.Text = "&Record";
this.checkboxRecord.CheckedChanged += new System.EventHandler(this.checkboxRecord_CheckedChanged);
//
// buttonSoundfile
//
this.buttonSoundfile.Location = new System.Drawing.Point(10, 11);
this.buttonSoundfile.Name = "buttonSoundfile";
this.buttonSoundfile.Size = new System.Drawing.Size(78, 21);
this.buttonSoundfile.TabIndex = 3;
this.buttonSoundfile.Text = "Sound &file...";
this.buttonSoundfile.Click += new System.EventHandler(this.buttonSoundfile_Click);
//
// labelFilename
//
this.labelFilename.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.labelFilename.Location = new System.Drawing.Point(96, 11);
this.labelFilename.Name = "labelFilename";
this.labelFilename.Size = new System.Drawing.Size(348, 21);
this.labelFilename.TabIndex = 4;
this.labelFilename.Text = "No file loaded.";
this.labelFilename.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.labelFilename.Click += new System.EventHandler(this.labelFilename_Click);
//
// MainForm
//
this.AcceptButton = this.buttonSoundfile;
this.ClientSize = new System.Drawing.Size(454, 77);
this.Controls.Add(this.labelStatic);
this.Controls.Add(this.labelMainInputformatText);
this.Controls.Add(this.checkboxRecord);
this.Controls.Add(this.buttonSoundfile);
this.Controls.Add(this.labelFilename);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Name = "MainForm";
this.Text = "CaptureSound3";
this.Closing += new System.ComponentModel.CancelEventHandler(this.MainForm_Closing);
this.ResumeLayout(false);
}
#endregion
private void InitDirectSound()
{
CaptureBufferSize = 0;
NotifySize = 0;
// Create DirectSound.Capture using the preferred capture device
try
{
applicationDevice = new Capture(CaptureDeviceGuid);
}
catch {}
}
void CreateCaptureBuffer()
{
//-----------------------------------------------------------------------------
// Name: CreateCaptureBuffer()
// Desc: Creates a capture buffer and sets the format
//-----------------------------------------------------------------------------
CaptureBufferDescription dscheckboxd = new CaptureBufferDescription();
if (null != applicationNotify)
{
applicationNotify.Dispose();
applicationNotify = null;
}
if (null != applicationBuffer)
{
applicationBuffer.Dispose();
applicationBuffer = null;
}
if (0 == InputFormat.Channels)
return;
// Set the notification size
NotifySize = (1024 > InputFormat.AverageBytesPerSecond / 8) ? 1024 : (InputFormat.AverageBytesPerSecond / 8);
NotifySize -= NotifySize % InputFormat.BlockAlign;
// Set the buffer sizes
CaptureBufferSize = NotifySize * NumberRecordNotifications;
// Create the capture buffer
dscheckboxd.BufferBytes = CaptureBufferSize;
InputFormat.FormatTag = WaveFormatTag.Pcm;
dscheckboxd.Format = InputFormat; // Set the format during creatation
applicationBuffer = new CaptureBuffer(dscheckboxd, applicationDevice);
NextCaptureOffset = 0;
InitNotifications();
}
void InitNotifications()
{
//-----------------------------------------------------------------------------
// Name: InitNotifications()
// Desc: Inits the notifications on the capture buffer which are handled
// in the notify thread.
//-----------------------------------------------------------------------------
if (null == applicationBuffer)
throw new NullReferenceException();
// Create a thread to monitor the notify events
if (null == NotifyThread)
{
NotifyThread = new Thread(new ThreadStart(WaitThread));
Capturing = true;
NotifyThread.Start();
// Create a notification event, for when the sound stops playing
NotificationEvent = new AutoResetEvent(false);
}
// Setup the notification positions
for (int i = 0; i < NumberRecordNotifications; i++)
{
PositionNotify[i].Offset = (NotifySize * i) + NotifySize - 1;
PositionNotify[i].EventNotifyHandle = NotificationEvent.Handle;
}
applicationNotify = new Notify(applicationBuffer);
// Tell DirectSound when to notify the app. The notification will come in the from
// of signaled events that are handled in the notify thread.
applicationNotify.SetNotificationPositions(PositionNotify, NumberRecordNotifications);
}
private void checkboxRecord_CheckedChanged(object sender, System.EventArgs e)
{
Recording = !Recording;
StartOrStopRecord(Recording);
if (!Recording)
checkboxRecord.Enabled = false;
}
void StartOrStopRecord(bool StartRecording)
{
//-----------------------------------------------------------------------------
// Name: StartOrStopRecord()
// Desc: Starts or stops the capture buffer from recording
//-----------------------------------------------------------------------------
if (StartRecording)
{
// Create a capture buffer, and tell the capture
// buffer to start recording
CreateCaptureBuffer();
applicationBuffer.Start(true);
}
else
{
// Stop the buffer, and read any data that was not
// caught by a notification
applicationBuffer.Stop();
RecordCapturedData();
Writer.Seek(4, SeekOrigin.Begin); // Seek to the length descriptor of the RIFF file.
Writer.Write((int)(SampleCount + 36)); // Write the file length, minus first 8 bytes of RIFF description.
Writer.Seek(40, SeekOrigin.Begin); // Seek to the data length descriptor of the RIFF file.
Writer.Write(SampleCount); // Write the length of the sample data in bytes.
Writer.Close(); // Close the file now.
Writer = null; // Set the writer to null.
WaveFile = null; // Set the FileStream to null.
}
}
void CreateRIFF()
{
/**************************************************************************
Here is where the file will be created. A
wave file is a RIFF file, which has chunks
of data that describe what the file contains.
A wave RIFF file is put together like this:
The 12 byte RIFF chunk is constructed like this:
Bytes 0 - 3 : 'R' 'I' 'F' 'F'
Bytes 4 - 7 : Length of file, minus the first 8 bytes of the RIFF description.
(4 bytes for "WAVE" + 24 bytes for format chunk length +
8 bytes for data chunk description + actual sample data size.)
Bytes 8 - 11: 'W' 'A' 'V' 'E'
The 24 byte FORMAT chunk is constructed like this:
Bytes 0 - 3 : 'f' 'm' 't' ' '
Bytes 4 - 7 : The format chunk length. This is always 16.
Bytes 8 - 9 : File padding. Always 1.
Bytes 10- 11: Number of channels. Either 1 for mono, or 2 for stereo.
Bytes 12- 15: Sample rate.
Bytes 16- 19: Number of bytes per second.
Bytes 20- 21: Bytes per sample. 1 for 8 bit mono, 2 for 8 bit stereo or
16 bit mono, 4 for 16 bit stereo.
Bytes 22- 23: Number of bits per sample.
The DATA chunk is constructed like this:
Bytes 0 - 3 : 'd' 'a' 't' 'a'
Bytes 4 - 7 : Length of data, in bytes.
Bytes 8 -...: Actual sample data.
***************************************************************************/
// Open up the wave file for writing.
WaveFile = new FileStream(FileName, FileMode.Create);
Writer = new BinaryWriter(WaveFile);
// Set up file with RIFF chunk info.
char[] ChunkRiff = {'R','I','F','F'};
char[] ChunkType = {'W','A','V','E'};
char[] ChunkFmt = {'f','m','t',' '};
char[] ChunkData = {'d','a','t','a'};
short shPad = 1; // File padding
int nFormatChunkLength = 0x10; // Format chunk length.
int nLength = 0; // File length, minus first 8 bytes of RIFF description. This will be filled in later.
short shBytesPerSample = 0; // Bytes per sample.
// Figure out how many bytes there will be per sample.
if (8 == InputFormat.BitsPerSample && 1 == InputFormat.Channels)
shBytesPerSample = 1;
else if ((8 == InputFormat.BitsPerSample && 2 == InputFormat.Channels) || (16 == InputFormat.BitsPerSample && 1 == InputFormat.Channels))
shBytesPerSample = 2;
else if (16 == InputFormat.BitsPerSample && 2 == InputFormat.Channels)
shBytesPerSample = 4;
// Fill in the riff info for the wave file.
Writer.Write(ChunkRiff);
Writer.Write(nLength);
Writer.Write(ChunkType);
// Fill in the format info for the wave file.
Writer.Write(ChunkFmt);
Writer.Write(nFormatChunkLength);
Writer.Write(shPad);
Writer.Write(InputFormat.Channels);
Writer.Write(InputFormat.SamplesPerSecond);
Writer.Write(InputFormat.AverageBytesPerSecond);
Writer.Write(shBytesPerSample);
Writer.Write(InputFormat.BitsPerSample);
// Now fill in the data chunk.
Writer.Write(ChunkData);
Writer.Write((int)0); // The sample length will be written in later.
}
void RecordCapturedData()
{
//-----------------------------------------------------------------------------
// Name: RecordCapturedData()
// Desc: Copies data from the capture buffer to the output buffer
//-----------------------------------------------------------------------------
byte[] CaptureData = null;
int ReadPos;
int CapturePos;
int LockSize;
applicationBuffer.GetCurrentPosition(out CapturePos, out ReadPos);
LockSize = ReadPos - NextCaptureOffset;
if (LockSize < 0)
LockSize += CaptureBufferSize;
// Block align lock size so that we are always write on a boundary
LockSize -= (LockSize % NotifySize);
if (0 == LockSize)
return;
// Read the capture buffer.
CaptureData = (byte[])applicationBuffer.Read(NextCaptureOffset, typeof(byte), LockFlag.None, LockSize);
// Write the data into the wav file
Writer.Write(CaptureData, 0, CaptureData.Length);
// Update the number of samples, in bytes, of the file so far.
SampleCount += CaptureData.Length;
// Move the capture offset along
NextCaptureOffset += CaptureData.Length;
NextCaptureOffset %= CaptureBufferSize; // Circular buffer
}
private void buttonSoundfile_Click(object sender, System.EventArgs e)
{
OnCreateSoundFile();
}
private void OnCreateSoundFile()
{
//-----------------------------------------------------------------------------
// Name: OnCreateSoundFile()
// Desc: Called when the user requests to save to a sound file
//-----------------------------------------------------------------------------
SaveFileDialog ofd = new SaveFileDialog();
WaveFormat wf = new WaveFormat();
DialogResult result;
// Get the default media path (something like C:\WINDOWS\MEDIA)
if (string.Empty == Path)
Path = Environment.SystemDirectory.Substring(0, Environment.SystemDirectory.LastIndexOf("\\")) + "\\media";
if (Recording)
{
// Stop the capture and read any data that
// was not caught by a notification
StartOrStopRecord(false);
Recording = false;
}
ofd.DefaultExt = ".wav";
ofd.Filter = "Wave Files|*.wav|All Files|*.*";
ofd.FileName = FileName;
ofd.InitialDirectory = Path;
// Update the UI controls to show the sound as loading a file
checkboxRecord.Enabled = false;
labelFilename.Text = "Saving file...";
// Display the OpenFileName dialog. Then, try to load the specified file
result = ofd.ShowDialog(this);
if (DialogResult.Abort == result || DialogResult.Cancel == result)
{
labelFilename.Text = "Save aborted.";
return;
}
FileName = ofd.FileName;
try
{
CreateRIFF();
}
catch
{
labelFilename.Text = "Could not create wave file.";
return;
}
// Update the UI controls to show the sound as the file is loaded
labelFilename.Text = FileName;
checkboxRecord.Enabled = true;
// Remember the path for next time
Path = FileName.Substring(0, FileName.LastIndexOf("\\"));
}
private void WaitThread()
{
while(Capturing)
{
//Sit here and wait for a message to arrive
NotificationEvent.WaitOne(Timeout.Infinite, true);
RecordCapturedData();
}
}
private void labelMainInputformatText_Click(object sender, EventArgs e)
{
}
private void labelFilename_Click(object sender, EventArgs e)
{
}
private void labelStatic_Click(object sender, EventArgs e)
{
}
}
|
|
|
|
|
(pardon the formatting - Instant VB preserves original formatting and your C# code was formatted this way)
Imports Microsoft.VisualBasic
'----------------------------------------------------------------------------
' File: Main.cs
'
' Copyright (c) Microsoft Corp. All rights reserved.
'-----------------------------------------------------------------------------
Imports System
Imports System.IO
Imports System.Drawing
Imports System.Windows.Forms
Imports System.Threading
Imports Microsoft.DirectX
Imports Microsoft.DirectX.DirectSound
Public Class MainForm
Inherits Form
Private WithEvents labelMainInputformatText As Label
Private WithEvents checkboxRecord As CheckBox
Private WithEvents buttonSoundfile As Button
Private WithEvents labelFilename As Label
Private WithEvents labelStatic As Label
Public PositionNotify As BufferPositionNotify() = New BufferPositionNotify(NumberRecordNotifications){}
Public Const NumberRecordNotifications As Integer = 16
Public NotificationEvent As AutoResetEvent = Nothing
Public applicationBuffer As CaptureBuffer = Nothing
Public CaptureDeviceGuid As Guid = Guid.Empty
Public applicationDevice As Capture = Nothing
Private FileName As String = String.Empty
Public applicationNotify As Notify = Nothing
Private NotifyThread As Thread = Nothing
Private WaveFile As FileStream = Nothing
Private Writer As BinaryWriter = Nothing
Private Path As String = String.Empty
Public CaptureBufferSize As Integer = 0
Public NextCaptureOffset As Integer = 0
Private Recording As Boolean = False
Public InputFormat As WaveFormat
Private SampleCount As Integer = 0
Public NotifySize As Integer = 0
Private Capturing As Boolean = False
<STAThread> _
Public Shared Sub Main()
Try
Using form As MainForm = New MainForm()
form.ShowDialog()
End Using
Catch
End Try
End Sub
Private Sub MainForm_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
If Not Nothing Is NotificationEvent Then
Capturing = False
NotificationEvent.Set()
End If
If Not Nothing Is applicationBuffer Then
If applicationBuffer.Capturing Then
StartOrStopRecord(False)
End If
End If
End Sub
Public Sub New()
'
' Required for Windows Form Designer support
'
InitializeComponent()
Dim devices As DevicesForm = New DevicesForm(Me)
devices.ShowDialog(Me)
InitDirectSound()
If Nothing Is applicationDevice Then
Close()
Else
Dim formats As FormatsForm = New FormatsForm(Me)
If formats.ShowDialog(Me) = System.Windows.Forms.DialogResult.OK Then
If (1 = InputFormat.Channels) Then
labelMainInputformatText.Text = String.Format("{0} Hz, {1}-bit ", InputFormat.SamplesPerSecond, InputFormat.BitsPerSample) + ("Mono")
Else
labelMainInputformatText.Text = String.Format("{0} Hz, {1}-bit ", InputFormat.SamplesPerSecond, InputFormat.BitsPerSample) + ("Stereo")
End If
CreateCaptureBuffer()
Else
Me.Close()
End If
End If
End Sub
#Region "InitializeComponent code"
Private Sub InitializeComponent()
Me.labelStatic = New System.Windows.Forms.Label()
Me.labelMainInputformatText = New System.Windows.Forms.Label()
Me.checkboxRecord = New System.Windows.Forms.CheckBox()
Me.buttonSoundfile = New System.Windows.Forms.Button()
Me.labelFilename = New System.Windows.Forms.Label()
Me.SuspendLayout()
'
' labelStatic
'
Me.labelStatic.Location = New System.Drawing.Point(10, 46)
Me.labelStatic.Name = "labelStatic"
Me.labelStatic.Size = New System.Drawing.Size(75, 13)
Me.labelStatic.TabIndex = 0
Me.labelStatic.Text = "Input Format:"
'Me.labelStatic.Click += New System.EventHandler(Me.labelStatic_Click);
'
' labelMainInputformatText
'
Me.labelMainInputformatText.Location = New System.Drawing.Point(90, 46)
Me.labelMainInputformatText.Name = "labelMainInputformatText"
Me.labelMainInputformatText.Size = New System.Drawing.Size(262, 13)
Me.labelMainInputformatText.TabIndex = 1
'Me.labelMainInputformatText.Click += New System.EventHandler(Me.labelMainInputformatText_Click);
'
' checkboxRecord
'
Me.checkboxRecord.Appearance = System.Windows.Forms.Appearance.Button
Me.checkboxRecord.Enabled = False
Me.checkboxRecord.FlatStyle = System.Windows.Forms.FlatStyle.System
Me.checkboxRecord.Location = New System.Drawing.Point(369, 40)
Me.checkboxRecord.Name = "checkboxRecord"
Me.checkboxRecord.Size = New System.Drawing.Size(75, 23)
Me.checkboxRecord.TabIndex = 2
Me.checkboxRecord.Text = "&Record"
'Me.checkboxRecord.CheckedChanged += New System.EventHandler(Me.checkboxRecord_CheckedChanged);
'
' buttonSoundfile
'
Me.buttonSoundfile.Location = New System.Drawing.Point(10, 11)
Me.buttonSoundfile.Name = "buttonSoundfile"
Me.buttonSoundfile.Size = New System.Drawing.Size(78, 21)
Me.buttonSoundfile.TabIndex = 3
Me.buttonSoundfile.Text = "Sound &file..."
'Me.buttonSoundfile.Click += New System.EventHandler(Me.buttonSoundfile_Click);
'
' labelFilename
'
Me.labelFilename.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D
Me.labelFilename.Location = New System.Drawing.Point(96, 11)
Me.labelFilename.Name = "labelFilename"
Me.labelFilename.Size = New System.Drawing.Size(348, 21)
Me.labelFilename.TabIndex = 4
Me.labelFilename.Text = "No file loaded."
Me.labelFilename.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
'Me.labelFilename.Click += New System.EventHandler(Me.labelFilename_Click);
'
' MainForm
'
Me.AcceptButton = Me.buttonSoundfile
Me.ClientSize = New System.Drawing.Size(454, 77)
Me.Controls.Add(Me.labelStatic)
Me.Controls.Add(Me.labelMainInputformatText)
Me.Controls.Add(Me.checkboxRecord)
Me.Controls.Add(Me.buttonSoundfile)
Me.Controls.Add(Me.labelFilename)
Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog
Me.Name = "MainForm"
Me.Text = "CaptureSound3"
'Me.Closing += New System.ComponentModel.CancelEventHandler(Me.MainForm_Closing);
Me.ResumeLayout(False)
End Sub
#End Region
Private Sub InitDirectSound()
CaptureBufferSize = 0
NotifySize = 0
' Create DirectSound.Capture using the preferred capture device
Try
applicationDevice = New Capture(CaptureDeviceGuid)
Catch
End Try
End Sub
Private Sub CreateCaptureBuffer()
'-----------------------------------------------------------------------------
' Name: CreateCaptureBuffer()
' Desc: Creates a capture buffer and sets the format
'-----------------------------------------------------------------------------
Dim dscheckboxd As CaptureBufferDescription = New CaptureBufferDescription()
If Not Nothing Is applicationNotify Then
applicationNotify.Dispose()
applicationNotify = Nothing
End If
If Not Nothing Is applicationBuffer Then
applicationBuffer.Dispose()
applicationBuffer = Nothing
End If
If 0 = InputFormat.Channels Then
Return
End If
' Set the notification size
If (1024 > InputFormat.AverageBytesPerSecond / 8) Then
NotifySize = 1024
Else
NotifySize = (InputFormat.AverageBytesPerSecond / 8)
End If
NotifySize -= NotifySize Mod InputFormat.BlockAlign
' Set the buffer sizes
CaptureBufferSize = NotifySize * NumberRecordNotifications
' Create the capture buffer
dscheckboxd.BufferBytes = CaptureBufferSize
InputFormat.FormatTag = WaveFormatTag.Pcm
dscheckboxd.Format = InputFormat ' Set the format during creatation
applicationBuffer = New CaptureBuffer(dscheckboxd, applicationDevice)
NextCaptureOffset = 0
InitNotifications()
End Sub
Private Sub InitNotifications()
'-----------------------------------------------------------------------------
' Name: InitNotifications()
' Desc: Inits the notifications on the capture buffer which are handled
' in the notify thread.
'-----------------------------------------------------------------------------
If Nothing Is applicationBuffer Then
Throw New NullReferenceException()
End If
' Create a thread to monitor the notify events
If Nothing Is NotifyThread Then
NotifyThread = New Thread(New ThreadStart(AddressOf WaitThread))
Capturing = True
NotifyThread.Start()
' Create a notification event, for when the sound stops playing
NotificationEvent = New AutoResetEvent(False)
End If
' Setup the notification positions
For i As Integer = 0 To NumberRecordNotifications - 1
PositionNotify(i).Offset = (NotifySize * i) + NotifySize - 1
PositionNotify(i).EventNotifyHandle = NotificationEvent.Handle
Next i
applicationNotify = New Notify(applicationBuffer)
' Tell DirectSound when to notify the app. The notification will come in the from
' of signaled events that are handled in the notify thread.
applicationNotify.SetNotificationPositions(PositionNotify, NumberRecordNotifications)
End Sub
Private Sub checkboxRecord_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles checkboxRecord.CheckedChanged
Recording = Not Recording
StartOrStopRecord(Recording)
If (Not Recording) Then
checkboxRecord.Enabled = False
End If
End Sub
Private Sub StartOrStopRecord(ByVal StartRecording As Boolean)
'-----------------------------------------------------------------------------
' Name: StartOrStopRecord()
' Desc: Starts or stops the capture buffer from recording
'-----------------------------------------------------------------------------
If StartRecording Then
' Create a capture buffer, and tell the capture
' buffer to start recording
CreateCaptureBuffer()
applicationBuffer.Start(True)
Else
' Stop the buffer, and read any data that was not
' caught by a notification
applicationBuffer.Stop()
RecordCapturedData()
Writer.Seek(4, SeekOrigin.Begin) ' Seek to the length descriptor of the RIFF file.
Writer.Write(CInt(Fix(SampleCount + 36))) ' Write the file length, minus first 8 bytes of RIFF description.
Writer.Seek(40, SeekOrigin.Begin) ' Seek to the data length descriptor of the RIFF file.
Writer.Write(SampleCount) ' Write the length of the sample data in bytes.
Writer.Close() ' Close the file now.
Writer = Nothing ' Set the writer to null.
WaveFile = Nothing ' Set the FileStream to null.
End If
End Sub
Private Sub CreateRIFF()
'*************************************************************************
'
'Here is where the file will be created. A
'wave file is a RIFF file, which has chunks
'of data that describe what the file contains.
'A wave RIFF file is put together like this:
'
'The 12 byte RIFF chunk is constructed like this:
'Bytes 0 - 3 : 'R' 'I' 'F' 'F'
'Bytes 4 - 7 : Length of file, minus the first 8 bytes of the RIFF description.
'(4 bytes for "WAVE" + 24 bytes for format chunk length +
'8 bytes for data chunk description + actual sample data size.)
'Bytes 8 - 11: 'W' 'A' 'V' 'E'
'
'The 24 byte FORMAT chunk is constructed like this:
'Bytes 0 - 3 : 'f' 'm' 't' ' '
'Bytes 4 - 7 : The format chunk length. This is always 16.
'Bytes 8 - 9 : File padding. Always 1.
'Bytes 10- 11: Number of channels. Either 1 for mono, or 2 for stereo.
'Bytes 12- 15: Sample rate.
'Bytes 16- 19: Number of bytes per second.
'Bytes 20- 21: Bytes per sample. 1 for 8 bit mono, 2 for 8 bit stereo or
'16 bit mono, 4 for 16 bit stereo.
'Bytes 22- 23: Number of bits per sample.
'
'The DATA chunk is constructed like this:
'Bytes 0 - 3 : 'd' 'a' 't' 'a'
'Bytes 4 - 7 : Length of data, in bytes.
'Bytes 8 -...: Actual sample data.
'
'**************************************************************************
' Open up the wave file for writing.
WaveFile = New FileStream(FileName, FileMode.Create)
Writer = New BinaryWriter(WaveFile)
' Set up file with RIFF chunk info.
Dim ChunkRiff As Char() = {"R"c,"I"c,"F"c,"F"c}
Dim ChunkType As Char() = {"W"c,"A"c,"V"c,"E"c}
Dim ChunkFmt As Char() = {"f"c,"m"c,"t"c," "c}
Dim ChunkData As Char() = {"d"c,"a"c,"t"c,"a"c}
Dim shPad As Short = 1 ' File padding
Dim nFormatChunkLength As Integer = &H10 ' Format chunk length.
Dim nLength As Integer = 0 ' File length, minus first 8 bytes of RIFF description. This will be filled in later.
Dim shBytesPerSample As Short = 0 ' Bytes per sample.
' Figure out how many bytes there will be per sample.
If 8 = InputFormat.BitsPerSample AndAlso 1 = InputFormat.Channels Then
shBytesPerSample = 1
ElseIf (8 = InputFormat.BitsPerSample AndAlso 2 = InputFormat.Channels) OrElse (16 = InputFormat.BitsPerSample AndAlso 1 = InputFormat.Channels) Then
shBytesPerSample = 2
ElseIf 16 = InputFormat.BitsPerSample AndAlso 2 = InputFormat.Channels Then
shBytesPerSample = 4
End If
' Fill in the riff info for the wave file.
Writer.Write(ChunkRiff)
Writer.Write(nLength)
Writer.Write(ChunkType)
' Fill in the format info for the wave file.
Writer.Write(ChunkFmt)
Writer.Write(nFormatChunkLength)
Writer.Write(shPad)
Writer.Write(InputFormat.Channels)
Writer.Write(InputFormat.SamplesPerSecond)
Writer.Write(InputFormat.AverageBytesPerSecond)
Writer.Write(shBytesPerSample)
Writer.Write(InputFormat.BitsPerSample)
' Now fill in the data chunk.
Writer.Write(ChunkData)
Writer.Write(CInt(Fix(0))) ' The sample length will be written in later.
End Sub
Private Sub RecordCapturedData()
'-----------------------------------------------------------------------------
' Name: RecordCapturedData()
' Desc: Copies data from the capture buffer to the output buffer
'-----------------------------------------------------------------------------
Dim CaptureData As Byte() = Nothing
Dim ReadPos As Integer
Dim CapturePos As Integer
Dim LockSize As Integer
applicationBuffer.GetCurrentPosition(CapturePos, ReadPos)
LockSize = ReadPos - NextCaptureOffset
If LockSize < 0 Then
LockSize += CaptureBufferSize
End If
' Block align lock size so that we are always write on a boundary
LockSize -= (LockSize Mod NotifySize)
If 0 = LockSize Then
Return
End If
' Read the capture buffer.
CaptureData = CType(applicationBuffer.Read(NextCaptureOffset, GetType(Byte), LockFlag.None, LockSize), Byte())
' Write the data into the wav file
Writer.Write(CaptureData, 0, CaptureData.Length)
' Update the number of samples, in bytes, of the file so far.
SampleCount += CaptureData.Length
' Move the capture offset along
NextCaptureOffset += CaptureData.Length
NextCaptureOffset = NextCaptureOffset Mod CaptureBufferSize ' Circular buffer
End Sub
Private Sub buttonSoundfile_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles buttonSoundfile.Click
OnCreateSoundFile()
End Sub
Private Sub OnCreateSoundFile()
'-----------------------------------------------------------------------------
' Name: OnCreateSoundFile()
' Desc: Called when the user requests to save to a sound file
'-----------------------------------------------------------------------------
Dim ofd As SaveFileDialog = New SaveFileDialog()
Dim wf As WaveFormat = New WaveFormat()
Dim result As DialogResult
' Get the default media path (something like C:\WINDOWS\MEDIA)
If String.Empty = Path Then
Path = Environment.SystemDirectory.Substring(0, Environment.SystemDirectory.LastIndexOf("\")) & "\media"
End If
If Recording Then
' Stop the capture and read any data that
' was not caught by a notification
StartOrStopRecord(False)
Recording = False
End If
ofd.DefaultExt = ".wav"
ofd.Filter = "Wave Files|*.wav|All Files|*.*"
ofd.FileName = FileName
ofd.InitialDirectory = Path
' Update the UI controls to show the sound as loading a file
checkboxRecord.Enabled = False
labelFilename.Text = "Saving file..."
' Display the OpenFileName dialog. Then, try to load the specified file
result = ofd.ShowDialog(Me)
If System.Windows.Forms.DialogResult.Abort = result OrElse System.Windows.Forms.DialogResult.Cancel = result Then
labelFilename.Text = "Save aborted."
Return
End If
FileName = ofd.FileName
Try
CreateRIFF()
Catch
labelFilename.Text = "Could not create wave file."
Return
End Try
' Update the UI controls to show the sound as the file is loaded
labelFilename.Text = FileName
checkboxRecord.Enabled = True
' Remember the path for next time
Path = FileName.Substring(0, FileName.LastIndexOf("\"))
End Sub
Private Sub WaitThread()
Do While Capturing
'Sit here and wait for a message to arrive
NotificationEvent.WaitOne(Timeout.Infinite, True)
RecordCapturedData()
Loop
End Sub
Private Sub labelMainInputformatText_Click(ByVal sender As Object, ByVal e As EventArgs) Handles labelMainInputformatText.Click
End Sub
Private Sub labelFilename_Click(ByVal sender As Object, ByVal e As EventArgs) Handles labelFilename.Click
End Sub
Private Sub labelStatic_Click(ByVal sender As Object, ByVal e As EventArgs) Handles labelStatic.Click
End Sub
End Class
David Anton
http://www.tangiblesoftwaresolutions.com
Instant C#: VB to C# converter
Instant VB: C# to VB converter
C++ to C# Converter: converts C++ to C#
C++ to VB Converter: converts C++ to VB
C++ to Java Converter: converts C++ to Java
Instant C++: converts C# to C++/CLI and VB to C++/CLI
|
|
|
|
|
//----------------------------------------------------------------------------
// File: Formats.cs
//
// Copyright (c) Microsoft Corp. All rights reserved.
//-----------------------------------------------------------------------------
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Collections;
using Microsoft.DirectX;
using Microsoft.DirectX.DirectSound;
public class FormatsForm : Form
{
private struct FormatInfo
{
public WaveFormat format;
public override string ToString()
{
return ConvertWaveFormatToString(format);
}
};
private Button buttonOk;
private Button buttonCancel;
private ListBox lbFormatsInputListbox;
private Label labelStatic;
private MainForm mf = null;
private ArrayList formats = new ArrayList();
private bool[] InputFormatSupported = new bool[20];
public FormatsForm(MainForm mf)
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
this.mf = mf;
ScanAvailableInputFormats();
FillFormatListBox();
}
#region InitializeComponent code
private void InitializeComponent()
{
this.buttonOk = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.lbFormatsInputListbox = new System.Windows.Forms.ListBox();
this.labelStatic = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// buttonOk
//
this.buttonOk.Enabled = false;
this.buttonOk.Location = new System.Drawing.Point(10, 128);
this.buttonOk.Name = "buttonOk";
this.buttonOk.Size = new System.Drawing.Size(75, 23);
this.buttonOk.TabIndex = 0;
this.buttonOk.Text = "OK";
this.buttonOk.Click += new System.EventHandler(this.buttonOk_Click);
//
// buttonCancel
//
this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.buttonCancel.Location = new System.Drawing.Point(97, 128);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(75, 23);
this.buttonCancel.TabIndex = 1;
this.buttonCancel.Text = "Cancel";
this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click);
//
// lbFormatsInputListbox
//
this.lbFormatsInputListbox.Location = new System.Drawing.Point(10, 24);
this.lbFormatsInputListbox.Name = "lbFormatsInputListbox";
this.lbFormatsInputListbox.Size = new System.Drawing.Size(162, 95);
this.lbFormatsInputListbox.TabIndex = 2;
this.lbFormatsInputListbox.SelectedIndexChanged += new System.EventHandler(this.lbFormatsInputListbox_SelectedIndexChanged);
//
// labelStatic
//
this.labelStatic.Location = new System.Drawing.Point(10, 11);
this.labelStatic.Name = "labelStatic";
this.labelStatic.Size = new System.Drawing.Size(75, 13);
this.labelStatic.TabIndex = 3;
this.labelStatic.Text = "Input Format:";
this.labelStatic.Click += new System.EventHandler(this.labelStatic_Click);
//
// FormatsForm
//
this.AcceptButton = this.buttonOk;
this.CancelButton = this.buttonCancel;
this.ClientSize = new System.Drawing.Size(183, 170);
this.Controls.Add(this.buttonOk);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.lbFormatsInputListbox);
this.Controls.Add(this.labelStatic);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Name = "FormatsForm";
this.Text = "Select Capture Format";
this.ResumeLayout(false);
}
#endregion
private void ScanAvailableInputFormats()
{
//-----------------------------------------------------------------------------
// Name: ScanAvailableInputFormats()
// Desc: Tests to see if 20 different standard wave formats are supported by
// the capture device
//-----------------------------------------------------------------------------
WaveFormat format = new WaveFormat();
CaptureBufferDescription dscheckboxd = new CaptureBufferDescription();
CaptureBuffer pDSCaptureBuffer = null;
// This might take a second or two, so throw up the hourglass
Cursor = Cursors.WaitCursor;
format.FormatTag = WaveFormatTag.Pcm;
// Try 20 different standard formats to see if they are supported
for (int iIndex = 0; iIndex < 20; iIndex++)
{
GetWaveFormatFromIndex(iIndex, ref format);
// To test if a capture format is supported, try to create a
// new capture buffer using a specific format. If it works
// then the format is supported, otherwise not.
dscheckboxd.BufferBytes = format.AverageBytesPerSecond;
dscheckboxd.Format = format;
try
{
pDSCaptureBuffer = new CaptureBuffer(dscheckboxd, mf.applicationDevice);
InputFormatSupported[ iIndex ] = true;
}
catch
{
InputFormatSupported[ iIndex ] = false;
}
if (pDSCaptureBuffer != null)
pDSCaptureBuffer.Dispose();
}
Cursor = Cursors.Default;
}
private void GetWaveFormatFromIndex(int Index, ref WaveFormat format)
{
//-----------------------------------------------------------------------------
// Name: GetWaveFormatFromIndex()
// Desc: Returns 20 different wave formats based on Index
//-----------------------------------------------------------------------------
int SampleRate = Index / 4;
int iType = Index % 4;
switch (SampleRate)
{
case 0: format.SamplesPerSecond = 48000; break;
case 1: format.SamplesPerSecond = 44100; break;
case 2: format.SamplesPerSecond = 22050; break;
case 3: format.SamplesPerSecond = 11025; break;
case 4: format.SamplesPerSecond = 8000; break;
}
switch (iType)
{
case 0: format.BitsPerSample = 8; format.Channels = 1; break;
case 1: format.BitsPerSample = 16; format.Channels = 1; break;
case 2: format.BitsPerSample = 8; format.Channels = 2; break;
case 3: format.BitsPerSample = 16; format.Channels = 2; break;
}
format.BlockAlign = (short)(format.Channels * (format.BitsPerSample / 8));
format.AverageBytesPerSecond = format.BlockAlign * format.SamplesPerSecond;
}
void FillFormatListBox()
{
//-----------------------------------------------------------------------------
// Name: FillFormatListBox()
// Desc: Fills the format list box based on the availible formats
//-----------------------------------------------------------------------------
FormatInfo info = new FormatInfo();
string strFormatName = string.Empty;
WaveFormat format = new WaveFormat();
for (int iIndex = 0; iIndex < InputFormatSupported.Length; iIndex++)
{
if (true == InputFormatSupported[iIndex])
{
// Turn the index into a WaveFormat then turn that into a
// string and put the string in the listbox
GetWaveFormatFromIndex(iIndex, ref format);
info.format = format;
formats.Add(info);
}
}
lbFormatsInputListbox.DataSource = formats;
}
private static string ConvertWaveFormatToString(WaveFormat format)
{
//-----------------------------------------------------------------------------
// Name: ConvertWaveFormatToString()
// Desc: Converts a wave format to a text string
//-----------------------------------------------------------------------------
return format.SamplesPerSecond + " Hz, " +
format.BitsPerSample + "-bit " +
((format.Channels == 1) ? "Mono" : "Stereo");
}
private void FormatsOK()
{
//-----------------------------------------------------------------------------
// Name: FormatsOK()
// Desc: Stores the capture buffer format based on what was selected
//-----------------------------------------------------------------------------
mf.InputFormat = ((FormatInfo)formats[lbFormatsInputListbox.SelectedIndex]).format;
this.DialogResult = DialogResult.OK;
Close();
}
private void buttonOk_Click(object sender, System.EventArgs e)
{
FormatsOK();
}
private void lbFormatsInputListbox_SelectedIndexChanged(object sender, System.EventArgs e)
{
buttonOk.Enabled = true;
}
private void buttonCancel_Click(object sender, EventArgs e)
{
}
private void labelStatic_Click(object sender, EventArgs e)
{
}
}
|
|
|
|
|
(via Instant VB)
Imports Microsoft.VisualBasic
'----------------------------------------------------------------------------
' File: Formats.cs
'
' Copyright (c) Microsoft Corp. All rights reserved.
'-----------------------------------------------------------------------------
Imports System
Imports System.Drawing
Imports System.Windows.Forms
Imports System.Collections
Imports Microsoft.DirectX
Imports Microsoft.DirectX.DirectSound
Public Class FormatsForm
Inherits Form
Private Structure FormatInfo
Public format As WaveFormat
Public Overrides Function ToString() As String
Return ConvertWaveFormatToString(format)
End Function
End Structure
Private WithEvents buttonOk As Button
Private WithEvents buttonCancel As Button
Private WithEvents lbFormatsInputListbox As ListBox
Private WithEvents labelStatic As Label
Private mf As MainForm = Nothing
Private formats As ArrayList = New ArrayList()
Private InputFormatSupported As Boolean() = New Boolean(19){}
Public Sub New(ByVal mf As MainForm)
'
' Required for Windows Form Designer support
'
InitializeComponent()
Me.mf = mf
ScanAvailableInputFormats()
FillFormatListBox()
End Sub
#Region "InitializeComponent code"
Private Sub InitializeComponent()
Me.buttonOk = New System.Windows.Forms.Button()
Me.buttonCancel = New System.Windows.Forms.Button()
Me.lbFormatsInputListbox = New System.Windows.Forms.ListBox()
Me.labelStatic = New System.Windows.Forms.Label()
Me.SuspendLayout()
'
' buttonOk
'
Me.buttonOk.Enabled = False
Me.buttonOk.Location = New System.Drawing.Point(10, 128)
Me.buttonOk.Name = "buttonOk"
Me.buttonOk.Size = New System.Drawing.Size(75, 23)
Me.buttonOk.TabIndex = 0
Me.buttonOk.Text = "OK"
'Me.buttonOk.Click += New System.EventHandler(Me.buttonOk_Click);
'
' buttonCancel
'
Me.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel
Me.buttonCancel.Location = New System.Drawing.Point(97, 128)
Me.buttonCancel.Name = "buttonCancel"
Me.buttonCancel.Size = New System.Drawing.Size(75, 23)
Me.buttonCancel.TabIndex = 1
Me.buttonCancel.Text = "Cancel"
'Me.buttonCancel.Click += New System.EventHandler(Me.buttonCancel_Click);
'
' lbFormatsInputListbox
'
Me.lbFormatsInputListbox.Location = New System.Drawing.Point(10, 24)
Me.lbFormatsInputListbox.Name = "lbFormatsInputListbox"
Me.lbFormatsInputListbox.Size = New System.Drawing.Size(162, 95)
Me.lbFormatsInputListbox.TabIndex = 2
'Me.lbFormatsInputListbox.SelectedIndexChanged += New System.EventHandler(Me.lbFormatsInputListbox_SelectedIndexChanged);
'
' labelStatic
'
Me.labelStatic.Location = New System.Drawing.Point(10, 11)
Me.labelStatic.Name = "labelStatic"
Me.labelStatic.Size = New System.Drawing.Size(75, 13)
Me.labelStatic.TabIndex = 3
Me.labelStatic.Text = "Input Format:"
'Me.labelStatic.Click += New System.EventHandler(Me.labelStatic_Click);
'
' FormatsForm
'
Me.AcceptButton = Me.buttonOk
Me.CancelButton = Me.buttonCancel
Me.ClientSize = New System.Drawing.Size(183, 170)
Me.Controls.Add(Me.buttonOk)
Me.Controls.Add(Me.buttonCancel)
Me.Controls.Add(Me.lbFormatsInputListbox)
Me.Controls.Add(Me.labelStatic)
Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog
Me.Name = "FormatsForm"
Me.Text = "Select Capture Format"
Me.ResumeLayout(False)
End Sub
#End Region
Private Sub ScanAvailableInputFormats()
'-----------------------------------------------------------------------------
' Name: ScanAvailableInputFormats()
' Desc: Tests to see if 20 different standard wave formats are supported by
' the capture device
'-----------------------------------------------------------------------------
Dim format As WaveFormat = New WaveFormat()
Dim dscheckboxd As CaptureBufferDescription = New CaptureBufferDescription()
Dim pDSCaptureBuffer As CaptureBuffer = Nothing
' This might take a second or two, so throw up the hourglass
Cursor = Cursors.WaitCursor
format.FormatTag = WaveFormatTag.Pcm
' Try 20 different standard formats to see if they are supported
For iIndex As Integer = 0 To 19
GetWaveFormatFromIndex(iIndex, format)
' To test if a capture format is supported, try to create a
' new capture buffer using a specific format. If it works
' then the format is supported, otherwise not.
dscheckboxd.BufferBytes = format.AverageBytesPerSecond
dscheckboxd.Format = format
Try
pDSCaptureBuffer = New CaptureBuffer(dscheckboxd, mf.applicationDevice)
InputFormatSupported(iIndex) = True
Catch
InputFormatSupported(iIndex) = False
End Try
If Not pDSCaptureBuffer Is Nothing Then
pDSCaptureBuffer.Dispose()
End If
Next iIndex
Cursor = Cursors.Default
End Sub
Private Sub GetWaveFormatFromIndex(ByVal Index As Integer, ByRef format As WaveFormat)
'-----------------------------------------------------------------------------
' Name: GetWaveFormatFromIndex()
' Desc: Returns 20 different wave formats based on Index
'-----------------------------------------------------------------------------
Dim SampleRate As Integer = Index \ 4
Dim iType As Integer = Index Mod 4
Select Case SampleRate
Case 0
format.SamplesPerSecond = 48000
Case 1
format.SamplesPerSecond = 44100
Case 2
format.SamplesPerSecond = 22050
Case 3
format.SamplesPerSecond = 11025
Case 4
format.SamplesPerSecond = 8000
End Select
Select Case iType
Case 0
format.BitsPerSample = 8
format.Channels = 1
Case 1
format.BitsPerSample = 16
format.Channels = 1
Case 2
format.BitsPerSample = 8
format.Channels = 2
Case 3
format.BitsPerSample = 16
format.Channels = 2
End Select
format.BlockAlign = CShort(Fix(format.Channels * (format.BitsPerSample / 8)))
format.AverageBytesPerSecond = format.BlockAlign * format.SamplesPerSecond
End Sub
Private Sub FillFormatListBox()
'-----------------------------------------------------------------------------
' Name: FillFormatListBox()
' Desc: Fills the format list box based on the availible formats
'-----------------------------------------------------------------------------
Dim info As FormatInfo = New FormatInfo()
Dim strFormatName As String = String.Empty
Dim format As WaveFormat = New WaveFormat()
For iIndex As Integer = 0 To InputFormatSupported.Length - 1
If True = InputFormatSupported(iIndex) Then
' Turn the index into a WaveFormat then turn that into a
' string and put the string in the listbox
GetWaveFormatFromIndex(iIndex, format)
info.format = format
formats.Add(info)
End If
Next iIndex
lbFormatsInputListbox.DataSource = formats
End Sub
Private Shared Function ConvertWaveFormatToString(ByVal format As WaveFormat) As String
'-----------------------------------------------------------------------------
' Name: ConvertWaveFormatToString()
' Desc: Converts a wave format to a text string
'-----------------------------------------------------------------------------
If (format.Channels = 1) Then
Return format.SamplesPerSecond & " Hz, " & format.BitsPerSample & "-bit " & ("Mono")
Else
Return format.SamplesPerSecond & " Hz, " & format.BitsPerSample & "-bit " & ("Stereo")
End If
End Function
Private Sub FormatsOK()
'-----------------------------------------------------------------------------
' Name: FormatsOK()
' Desc: Stores the capture buffer format based on what was selected
'-----------------------------------------------------------------------------
mf.InputFormat = (CType(formats(lbFormatsInputListbox.SelectedIndex), FormatInfo)).format
Me.DialogResult = System.Windows.Forms.DialogResult.OK
Close()
End Sub
Private Sub buttonOk_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles buttonOk.Click
FormatsOK()
End Sub
Private Sub lbFormatsInputListbox_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles lbFormatsInputListbox.SelectedIndexChanged
buttonOk.Enabled = True
End Sub
Private Sub buttonCancel_Click(ByVal sender As Object, ByVal e As EventArgs) Handles buttonCancel.Click
End Sub
Private Sub labelStatic_Click(ByVal sender As Object, ByVal e As EventArgs) Handles labelStatic.Click
End Sub
End Class
David Anton
http://www.tangiblesoftwaresolutions.com
Instant C#: VB to C# converter
Instant VB: C# to VB converter
C++ to C# Converter: converts C++ to C#
C++ to VB Converter: converts C++ to VB
C++ to Java Converter: converts C++ to Java
Instant C++: converts C# to C++/CLI and VB to C++/CLI
|
|
|
|
|
//----------------------------------------------------------------------------
// File: Devices.cs
//
// Copyright (c) Microsoft Corp. All rights reserved.
//-----------------------------------------------------------------------------
using System;
using System.Drawing;
using System.Windows.Forms;
using Microsoft.DirectX.DirectSound;
public class DevicesForm : Form
{
private Button buttonOk;
private Button buttonCancel;
private Label labelStatic;
private ComboBox comboboxCaptureDeviceCombo;
private MainForm mf = null;
CaptureDevicesCollection devices = new CaptureDevicesCollection();
public DevicesForm(MainForm mf)
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
this.mf = mf;
foreach (DeviceInformation info in devices)
comboboxCaptureDeviceCombo.Items.Add(info.Description);
comboboxCaptureDeviceCombo.SelectedIndex = 0;
}
#region InitializeComponent code
private void InitializeComponent()
{
this.buttonOk = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.labelStatic = new System.Windows.Forms.Label();
this.comboboxCaptureDeviceCombo = new System.Windows.Forms.ComboBox();
this.SuspendLayout();
//
// buttonOk
//
this.buttonOk.Location = new System.Drawing.Point(10, 41);
this.buttonOk.Name = "buttonOk";
this.buttonOk.Size = new System.Drawing.Size(75, 23);
this.buttonOk.TabIndex = 0;
this.buttonOk.Text = "OK";
this.buttonOk.Click += new System.EventHandler(this.buttonOk_Click);
//
// buttonCancel
//
this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.buttonCancel.Location = new System.Drawing.Point(231, 41);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(75, 23);
this.buttonCancel.TabIndex = 1;
this.buttonCancel.Text = "Cancel";
this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click);
//
// labelStatic
//
this.labelStatic.Location = new System.Drawing.Point(0, 14);
this.labelStatic.Name = "labelStatic";
this.labelStatic.Size = new System.Drawing.Size(88, 13);
this.labelStatic.TabIndex = 2;
this.labelStatic.Text = "Capture Device:";
this.labelStatic.Click += new System.EventHandler(this.labelStatic_Click);
//
// comboboxCaptureDeviceCombo
//
this.comboboxCaptureDeviceCombo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboboxCaptureDeviceCombo.Location = new System.Drawing.Point(93, 11);
this.comboboxCaptureDeviceCombo.Name = "comboboxCaptureDeviceCombo";
this.comboboxCaptureDeviceCombo.Size = new System.Drawing.Size(213, 21);
this.comboboxCaptureDeviceCombo.Sorted = true;
this.comboboxCaptureDeviceCombo.TabIndex = 3;
this.comboboxCaptureDeviceCombo.SelectedIndexChanged += new System.EventHandler(this.comboboxCaptureDeviceCombo_SelectedIndexChanged);
//
// DevicesForm
//
this.AcceptButton = this.buttonOk;
this.CancelButton = this.buttonCancel;
this.ClientSize = new System.Drawing.Size(316, 79);
this.Controls.Add(this.buttonOk);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.labelStatic);
this.Controls.Add(this.comboboxCaptureDeviceCombo);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Name = "DevicesForm";
this.Text = "Select Capture Device";
this.ResumeLayout(false);
}
#endregion
private void buttonOk_Click(object sender, System.EventArgs e)
{
if (0 < comboboxCaptureDeviceCombo.Items.Count)
mf.CaptureDeviceGuid = devices[0].DriverGuid;
Close();
}
private void buttonCancel_Click(object sender, EventArgs e)
{
}
private void labelStatic_Click(object sender, EventArgs e)
{
}
private void comboboxCaptureDeviceCombo_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
|
|
|
|
|
//--------------------------------------------------------------------------------------
// File: AssemblyInfo.cs
//
// Assembly information for all managed samples
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------
using System;
using System.Security;
using System.Security.Permissions;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
// Set assembly information
[assembly: AssemblyTitle("Microsoft DirectX SDK Sample")]
[assembly: AssemblyDescription("Sample Code for the Microsoft DirectX SDK")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("DirectX SDK")]
[assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation. All rights reserved.")]
// Update version
[assembly: AssemblyVersion("9.12.589.0000")]
// We will use UInt which isn't CLS compliant, possible unsafe code as well
[assembly: CLSCompliant(false)]
[assembly: ComVisible(false)]
// Security information
[assembly: SecurityPermissionAttribute(SecurityAction.RequestMinimum, UnmanagedCode=true)]
[assembly: SecurityPermissionAttribute(SecurityAction.RequestMinimum, Execution=true)]
// We want to be able to read the registry key
[assembly: RegistryPermissionAttribute(SecurityAction.RequestMinimum,Read="HKEY_LOCAL_MACHINE\\Software\\Microsoft\\DirectX SDK")]
|
|
|
|
|
(via Instant VB)
'--------------------------------------------------------------------------------------
' File: AssemblyInfo.cs
'
' Assembly information for all managed samples
'
' Copyright (c) Microsoft Corporation. All rights reserved.
'--------------------------------------------------------------------------------------
Imports System
Imports System.Security
Imports System.Security.Permissions
Imports System.Reflection
Imports System.Runtime.InteropServices
Imports System.Runtime.CompilerServices
' Set assembly information
<Assembly: AssemblyTitle("Microsoft DirectX SDK Sample")>
<Assembly: AssemblyDescription("Sample Code for the Microsoft DirectX SDK")>
<Assembly: AssemblyCompany("Microsoft")>
<Assembly: AssemblyProduct("DirectX SDK")>
<Assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation. All rights reserved.")>
' Update version
<Assembly: AssemblyVersion("9.12.589.0000")>
' We will use UInt which isn't CLS compliant, possible unsafe code as well
<Assembly: CLSCompliant(False)>
<Assembly: ComVisible(False)>
' Security information
<Assembly: SecurityPermissionAttribute(SecurityAction.RequestMinimum, UnmanagedCode:=True)>
<Assembly: SecurityPermissionAttribute(SecurityAction.RequestMinimum, Execution:=True)>
' We want to be able to read the registry key
<Assembly: RegistryPermissionAttribute(SecurityAction.RequestMinimum,Read:="HKEY_LOCAL_MACHINE\Software\Microsoft\DirectX SDK")>
David Anton
http://www.tangiblesoftwaresolutions.com
Instant C#: VB to C# converter
Instant VB: C# to VB converter
C++ to C# Converter: converts C++ to C#
C++ to VB Converter: converts C++ to VB
C++ to Java Converter: converts C++ to Java
Instant C++: converts C# to C++/CLI and VB to C++/CLI
|
|
|
|
|
(via Instant VB)
'----------------------------------------------------------------------------
' File: Devices.cs
'
' Copyright (c) Microsoft Corp. All rights reserved.
'-----------------------------------------------------------------------------
Imports System
Imports System.Drawing
Imports System.Windows.Forms
Imports Microsoft.DirectX.DirectSound
Public Class DevicesForm
Inherits Form
Private WithEvents buttonOk As Button
Private WithEvents buttonCancel As Button
Private WithEvents labelStatic As Label
Private WithEvents comboboxCaptureDeviceCombo As ComboBox
Private mf As MainForm = Nothing
Private devices As CaptureDevicesCollection = New CaptureDevicesCollection()
Public Sub New(ByVal mf As MainForm)
'
' Required for Windows Form Designer support
'
InitializeComponent()
Me.mf = mf
For Each info As DeviceInformation In devices
comboboxCaptureDeviceCombo.Items.Add(info.Description)
Next info
comboboxCaptureDeviceCombo.SelectedIndex = 0
End Sub
#Region "InitializeComponent code"
Private Sub InitializeComponent()
Me.buttonOk = New System.Windows.Forms.Button()
Me.buttonCancel = New System.Windows.Forms.Button()
Me.labelStatic = New System.Windows.Forms.Label()
Me.comboboxCaptureDeviceCombo = New System.Windows.Forms.ComboBox()
Me.SuspendLayout()
'
' buttonOk
'
Me.buttonOk.Location = New System.Drawing.Point(10, 41)
Me.buttonOk.Name = "buttonOk"
Me.buttonOk.Size = New System.Drawing.Size(75, 23)
Me.buttonOk.TabIndex = 0
Me.buttonOk.Text = "OK"
'Me.buttonOk.Click += New System.EventHandler(Me.buttonOk_Click);
'
' buttonCancel
'
Me.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel
Me.buttonCancel.Location = New System.Drawing.Point(231, 41)
Me.buttonCancel.Name = "buttonCancel"
Me.buttonCancel.Size = New System.Drawing.Size(75, 23)
Me.buttonCancel.TabIndex = 1
Me.buttonCancel.Text = "Cancel"
'Me.buttonCancel.Click += New System.EventHandler(Me.buttonCancel_Click);
'
' labelStatic
'
Me.labelStatic.Location = New System.Drawing.Point(0, 14)
Me.labelStatic.Name = "labelStatic"
Me.labelStatic.Size = New System.Drawing.Size(88, 13)
Me.labelStatic.TabIndex = 2
Me.labelStatic.Text = "Capture Device:"
'Me.labelStatic.Click += New System.EventHandler(Me.labelStatic_Click);
'
' comboboxCaptureDeviceCombo
'
Me.comboboxCaptureDeviceCombo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList
Me.comboboxCaptureDeviceCombo.Location = New System.Drawing.Point(93, 11)
Me.comboboxCaptureDeviceCombo.Name = "comboboxCaptureDeviceCombo"
Me.comboboxCaptureDeviceCombo.Size = New System.Drawing.Size(213, 21)
Me.comboboxCaptureDeviceCombo.Sorted = True
Me.comboboxCaptureDeviceCombo.TabIndex = 3
'Me.comboboxCaptureDeviceCombo.SelectedIndexChanged += New System.EventHandler(Me.comboboxCaptureDeviceCombo_SelectedIndexChanged);
'
' DevicesForm
'
Me.AcceptButton = Me.buttonOk
Me.CancelButton = Me.buttonCancel
Me.ClientSize = New System.Drawing.Size(316, 79)
Me.Controls.Add(Me.buttonOk)
Me.Controls.Add(Me.buttonCancel)
Me.Controls.Add(Me.labelStatic)
Me.Controls.Add(Me.comboboxCaptureDeviceCombo)
Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog
Me.Name = "DevicesForm"
Me.Text = "Select Capture Device"
Me.ResumeLayout(False)
End Sub
#End Region
Private Sub buttonOk_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles buttonOk.Click
If 0 < comboboxCaptureDeviceCombo.Items.Count Then
mf.CaptureDeviceGuid = devices(0).DriverGuid
End If
Close()
End Sub
Private Sub buttonCancel_Click(ByVal sender As Object, ByVal e As EventArgs) Handles buttonCancel.Click
End Sub
Private Sub labelStatic_Click(ByVal sender As Object, ByVal e As EventArgs) Handles labelStatic.Click
End Sub
Private Sub comboboxCaptureDeviceCombo_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles comboboxCaptureDeviceCombo.SelectedIndexChanged
End Sub
End Class
David Anton
http://www.tangiblesoftwaresolutions.com
Instant C#: VB to C# converter
Instant VB: C# to VB converter
C++ to C# Converter: converts C++ to C#
C++ to VB Converter: converts C++ to VB
C++ to Java Converter: converts C++ to Java
Instant C++: converts C# to C++/CLI and VB to C++/CLI
|
|
|
|
|
Thank you, your code has cleared up the errors I was getting. However, there still seems to be 1 problem. On the c# program the devices form comes up first but the main form comes up in vb. The reason seems to be that in the c# project the program starts in this function:
[STAThread]<br />
public static void Main()<br />
{<br />
try<br />
{<br />
using(MainForm form = new MainForm())<br />
{<br />
form.ShowDialog();<br />
}<br />
}<br />
catch{}<br />
}
But when I placed a bunch of breakpoints in my vb program it doesn't seem to enter the equivelent sub or any other procedure. This is true even when I click on a button in the main form.
ps I agree I don't like the original formatting and structuring of the program. This is actually an example program from the directx sdk which is only in c++ or c#. If I completely understood it I would probably just rewrite it before incorporating it into my program but unfortunately there's not much documention on it.
thank you again for your help.
|
|
|
|
|
Check the project properties ('Application' tab) for the VB project. You probably just need to select the right form as the startup form.
David Anton
http://www.tangiblesoftwaresolutions.com
Instant C#: VB to C# converter
Instant VB: C# to VB converter
C++ to C# Converter: converts C++ to C#
C++ to VB Converter: converts C++ to VB
C++ to Java Converter: converts C++ to Java
Instant C++: converts C# to C++/CLI and VB to C++/CLI
|
|
|
|
|
sCmd = Chr(&H8s) & Chr(&H2s)
|
|
|
|
|
try:
Console.WriteLine(sCmd)
and check the output.
|
|
|
|
|