Hey guys I managed to get some code what works fine but it uses console application

I have tried to convert it by hand and change things around to get it to work but with no avail!

I'm certain it should be simple but I may be wrong :(

Thanks guys
ignore the vb.net

If you think I'm trying to be spoon fed I can post my converted code but it doesn't work and probably 99.9% wrong

Code

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.CognitiveServices.Speech;
using Microsoft.CognitiveServices.Speech.Audio;

namespace ConsoleApp1

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
         private const string cKey = "key";

    private const string cRegion = "region";


    public static async Task SpeechToTextAsync()

    {

        var config = SpeechConfig.FromSubscription(cKey, cRegion);

        using (var recognizer = new SpeechRecognizer(config))

            await Recognize(recognizer);

    }

    private static async Task Recognize(SpeechRecognizer recognizer)

    {

        var result = await recognizer.RecognizeOnceAsync();


        if (result.Reason == ResultReason.RecognizedSpeech)
        {

            Console.WriteLine($"Recognized: {result.Text}");

            SendKeys.SendWait(result.Text);
        }

        else if (result.Reason == ResultReason.NoMatch)

            Console.WriteLine("Speech could not be recognized.");

        else if (result.Reason == ResultReason.Canceled)

        {

            var cancellation =

                CancellationDetails.FromResult(result);

            Console.WriteLine

                ($"Cancelled due to reason={cancellation.Reason}");

            if (cancellation.Reason == CancellationReason.Error)

            {

                Console.WriteLine

                    ($"Error code={cancellation.ErrorCode}");

                Console.WriteLine

                    ($"Error details={cancellation.ErrorDetails}");

                Console.WriteLine

                    ($"Did you update the subscription info?");

            }

        }

    }

    static void Main()

    {

        SpeechToTextAsync().Wait();
        Console.WriteLine("Please press enter to exit.");
        Console.ReadLine();

    }
}

Dani AI

Generated

is correct that starting from a WinForms project is the right move. The conversion posted by fails mainly for structural reasons: field and method declarations are nested inside an event handler (C# does not allow that), console-style blocking calls are present, and keyboard injection via SendKeys is brittle for GUI work. The practical fix is to move SDK/state to form scope, call recognition from an async event handler, and update UI controls directly on the UI thread.

Practical checklist

  • Create a WinForms project (Program.cs runs the message loop) and add the Microsoft.CognitiveServices.Speech NuGet package.
  • Move subscription key/region to private fields on the Form, not inside Form_Load.
  • Make recognition methods regular async methods at class scope (not nested). Call them from async event handlers (e.g., an async void startButton_Click), and use await rather than blocking with Wait() or ReadLine().
  • Prefer the SDK's continuous recognition and its events for interactive UI; handle Recognized / Canceled events rather than spamming SendKeys.
  • Update UI controls directly (use Invoke/BeginInvoke or let await resume on the UI context) to avoid cross-thread exceptions.
  • Do not hard-code production secrets in source control; use config/user-secrets.

Minimal pattern (UI-friendly, event-based)

private readonly string speechKey = "<KEY>";
private readonly string speechRegion = "<REGION>";
private SpeechRecognizer recognizer;

private void AppendTextSafe(string text)
{
    if (InvokeRequired) { BeginInvoke(new Action(() => AppendTextSafe(text))); return; }
    outputTextBox.AppendText(text + Environment.NewLine);
}

private async void startButton_Click(object sender, EventArgs e)
{
    var config = SpeechConfig.FromSubscription(speechKey, speechRegion);
    recognizer = new SpeechRecognizer(config);
    recognizer.Recognized += (s, evt) =>
    {
        if (evt.Result.Reason == ResultReason.RecognizedSpeech) AppendTextSafe(evt.Result.Text);
    };
    await recognizer.StartContinuousRecognitionAsync();
}

Troubleshooting notes: compile errors mentioning declarations inside methods indicate nested members — move them to the class level. If recognition fails, handle the Canceled event to read error details and verify subscription/region. For quick verification use a button that starts/stops recognition and a multiline TextBox for output instead of SendKeys or Console calls.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.