Hello I have a problem with my chatbox in my application, sometimes the chatbox gets stuck and wont open and sends text to speech commands while off screen and out of focus I'm not sure what causes it but can you fix it and resend the code?

'Chatbox is called on Form1 with this'
if (e.VirtualKeyCode == (int)VirtualKeyCode.RETURN)
{
    if (UseChatbox)
    {
        if (!chatBox.Visible)
        {
            chatBox.Show(this);
            chatBox.Poop();
        }
        else
        {
            // If chatBox is already visible, just bring it to front and focus the textbox
            chatBox.BringToFront();
        }
        chatBox.textBox1.Focus();
        chatBox.textBox1.Select();
        chatBox.BringFormToFront();
        textBox1.Select();
    }
}

'ChatBox.cs'
using Clowd.Clipboard;
using System;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ByteBreath
{
    public partial class ChatBox : Form
    {
        private Form1 _form1;

        private CancellationTokenSource animationCancellationTokenSource = new CancellationTokenSource();

        #region WinAPI imports and constants

        [DllImport("user32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);

        [DllImport("user32.dll")]
        private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

        [DllImport("user32.dll")]
        private static extern IntPtr GetForegroundWindow();

        [DllImport("user32.dll")]
        private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);

        [DllImport("user32.dll")]
        private static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool fAttach);

        [DllImport("kernel32.dll")]
        private static extern uint GetCurrentThreadId();

        private const int SW_RESTORE = 9;

        #endregion

        public ChatBox(Form1 form1)
        {
            InitializeComponent();

            TopMost = true;
            FormBorderStyle = FormBorderStyle.None;
            _form1 = form1;

            this.Load += ChatBox_Load;
            this.FormClosing += ChatBox_FormClosing;
        }

        /// <summary>
        /// Bring the window to the front.
        /// Restores if minimized, attaches thread input, and force focus to textBox1.
        /// </summary>
        public void BringFormToFront()
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action(BringFormToFront));
                return;
            }

            var hWnd = this.Handle;

            // If minimized, restore
            if (this.WindowState == FormWindowState.Minimized)
            {
                ShowWindow(hWnd, SW_RESTORE);
                // Let's also ensure the WindowState property is updated
                this.WindowState = FormWindowState.Normal;
            }

            IntPtr foregroundWindow = GetForegroundWindow();
            uint currentThreadId = GetCurrentThreadId();
            uint foregroundThreadId = GetWindowThreadProcessId(foregroundWindow, out _);

            // Attach our thread input to the foreground thread to allow SetForegroundWindow to succeed
            bool threadsAttached = false;
            if (currentThreadId != foregroundThreadId)
            {
                threadsAttached = AttachThreadInput(currentThreadId, foregroundThreadId, true);
            }

            // Bring to front and set foreground
            bool setForegroundResult = SetForegroundWindow(hWnd);

            if (threadsAttached)
            {
                AttachThreadInput(currentThreadId, foregroundThreadId, false);
            }

            // Activate the form - might be needed as fallback
            this.Activate();

            // Ensure the form is visible
            if (!this.Visible)
                this.Show();

            // Set focus on the textbox
            textBox1.Focus();
            textBox1.Select();
        }

        private async void ChatBox_Load(object sender, EventArgs e)
        {
            var workingArea = Screen.FromControl(this).WorkingArea;

            // Position form horizontally centered
            this.Left = (workingArea.Left + (workingArea.Width - this.Width) / 2);

            // Calculate targetTop so that textbox1 is at screen Y=workingArea.Top + 886
            int desiredTextBoxScreenY = workingArea.Top + 886;
            int targetTop = desiredTextBoxScreenY - textBox1.Location.Y;

            this.Top = workingArea.Bottom; // Start below screen

            this.Opacity = 1;
            if (!this.Visible)
                this.Show();

            await AnimateToPositionAsync(targetTop, true);
        }

        public async void Poop()
        {
            var workingArea = Screen.FromControl(this).WorkingArea;

            // Position form horizontally centered
            this.Left = (workingArea.Left + (workingArea.Width - this.Width) / 2);

            // Calculate targetTop so that textbox1 is at screen Y=workingArea.Top + 886
            int desiredTextBoxScreenY = workingArea.Top + 886;
            int targetTop = desiredTextBoxScreenY - textBox1.Location.Y;

            this.Top = workingArea.Bottom; // Start below screen

            this.Opacity = 1;
            if (!this.Visible)
                this.Show();

            await AnimateToPositionAsync(targetTop, true);
        }

        public async Task AnimateToPositionAsync(int targetTop, bool isShowing)
        {
            try
            {
                animationCancellationTokenSource.Cancel();
                animationCancellationTokenSource.Dispose();
            }
            catch
            {
                // ignored
            }

            animationCancellationTokenSource = new CancellationTokenSource();
            CancellationToken token = animationCancellationTokenSource.Token;

            var workingArea = Screen.FromControl(this).WorkingArea;
            int startTop = this.Top;
            int endTop = isShowing ? targetTop : workingArea.Bottom;

            int animationDurationMs = 180; // 180ms for snappy but smooth animation
            int frameIntervalMs = 1000 / 60; // 60 FPS
            int totalFrames = animationDurationMs / frameIntervalMs;

            for (int frame = 0; frame <= totalFrames; frame++)
            {
                if (token.IsCancellationRequested)
                    return;

                double progress = frame / (double)totalFrames;

                // Ease in/out cubic for smoothness
                double easedProgress = isShowing
                    ? 1 - Math.Pow(1 - progress, 3)   // ease out when showing
                    : Math.Pow(progress, 3);           // ease in when hiding

                int newTop = (int)(startTop + (endTop - startTop) * easedProgress);

                if (this.InvokeRequired)
                {
                    this.Invoke(new Action(() => this.Top = newTop));
                }
                else
                {
                    this.Top = newTop;
                }

                await Task.Delay(frameIntervalMs);
            }

            if (this.InvokeRequired)
            {
                this.Invoke(new Action(() => this.Top = endTop));
            }
            else
            {
                this.Top = endTop;
            }

            if (!isShowing)
            {
                if (this.InvokeRequired)
                {
                    this.Invoke(new Action(() => this.Hide()));
                }
                else
                {
                    this.Hide();
                }
            }
            else
            {
                BringFormToFront();
            }
        }

        private async void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Escape)
            {
                e.Handled = true;
                textBox1.Clear();
                await AnimateToPositionAsync(Screen.FromControl(this).WorkingArea.Bottom, false);
                return;
            }

            if (e.KeyChar == (char)Keys.Enter)
            {
                e.Handled = true;

                string text = textBox1.Text.Trim();
                if (!string.IsNullOrEmpty(text))
                {
                    if (_form1.FishSpeechMode)
                        _form1.GimmieFish(text, false);
                    if (_form1.ZonosTTSMode)
                        _form1.GimmieLocoz(text);
                    if (_form1.IndexTTSBool)
                        _form1.IndexAPI(text);

                    await ClipboardWpf.SetTextAsync(text);
                    textBox1.Clear();

                    await AnimateToPositionAsync(Screen.FromControl(this).WorkingArea.Bottom, false);
                }
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (Visible)
            {
                BringFormToFront();

                // Sync colors and background from _form1 as needed
                textBox1.ForeColor = _form1.textBox3.ForeColor;
                textBox1.BackColor = _form1.textBox3.BackColor;
                BackgroundImage = _form1.BackgroundImage;
                BackgroundImageLayout = _form1.BackgroundImageLayout;
            }
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            // Optional logic on textbox changes
        }

        private void ChatBox_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                animationCancellationTokenSource.Cancel();
                animationCancellationTokenSource.Dispose();
            }
            catch { }
        }
    }
}