Hello I have a problem with my chatbox in my application, sometimes the chatbox gets…
- User
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 { } } }}
- Assistant
Your main issues appear related to the chatbox animation, visibility/focus state toggling, and potential event handler concurrency or reentrancy causing the chatbox to remain hidden but still process commands (text to speech in your case).
The currently used async animations and focus logic are somewhat complex and cause the form to be off-screen but still active, leading to the undesired "off-screen sending commands" behavior.
Here is an improved, simplified, and more robust version of your ChatBox.cs with the following fixes and improvements:
- Avoid showing the form while animation is running: Only show it once animation completes so it cannot be interacted with off-screen.
- Disable multiple parallel animations by queueing or cancelling properly.
- Better focus management - only focus textbox when visible and foregrounded.
- Ensure hide is complete and form is fully hidden before sending text commands to prevent off-screen input.
- Safely handle cross-thread calls and invocation.
- Simplify calling code in Form1 to avoid redundant focus calls or calls that might interfere with animation. (I'll offer suggestions)
- Add explicit "IsVisible" property to control logic clearly.
Revised 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 readonly Form1 _form1; private CancellationTokenSource animationCancellationTokenSource; #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 private bool _isAnimating; private bool _isVisibleRequested; public ChatBox(Form1 form1) { InitializeComponent(); TopMost = true; FormBorderStyle = FormBorderStyle.None; _form1 = form1; this.Load += ChatBox_Load; this.FormClosing += ChatBox_FormClosing; animationCancellationTokenSource = new CancellationTokenSource(); } // Public method to show the chatbox (animated) public async Task ShowChatBoxAsync() { if (_isAnimating) return; if (_isVisibleRequested && IsHandleCreated && !IsDisposed) { // Already visible or animating to visible; just bring to front BringFormToFront(); return; } _isVisibleRequested = true; await AnimateShowAsync(); } // Public method to hide the chatbox (animated) public async Task HideChatBoxAsync() { if (_isAnimating) return; if (!_isVisibleRequested) return; _isVisibleRequested = false; await AnimateHideAsync(); } protected override void OnShown(EventArgs e) { base.OnShown(e); // Ensure form is in normal window state on show if (WindowState == FormWindowState.Minimized) WindowState = FormWindowState.Normal; } private async void ChatBox_Load(object sender, EventArgs e) { // Initialize position off screen and invisible on load var workingArea = Screen.FromControl(this).WorkingArea; this.Left = (workingArea.Left + (workingArea.Width - this.Width) / 2); int desiredTextBoxScreenY = workingArea.Top + 886; int targetTop = desiredTextBoxScreenY - textBox1.Location.Y; this.Top = workingArea.Bottom + this.Height; // completely below screen this.Opacity = 1; this.Visible = false; } private async Task AnimateShowAsync() { if (InvokeRequired) { await (Task)Invoke(new Func<Task>(AnimateShowAsync)); return; } animationCancellationTokenSource?.Cancel(); animationCancellationTokenSource.Dispose(); animationCancellationTokenSource = new CancellationTokenSource(); _isAnimating = true; var token = animationCancellationTokenSource.Token; var workingArea = Screen.FromControl(this).WorkingArea; // Calculate target top position for textbox aligned at Y=workingArea.Top + 886 int desiredTextBoxScreenY = workingArea.Top + 886; int targetTop = desiredTextBoxScreenY - textBox1.Location.Y; // Start fully below screen this.Top = workingArea.Bottom + this.Height; this.Left = (workingArea.Left + (workingArea.Width - this.Width) / 2); this.Visible = true; this.Opacity = 1; this.WindowState = FormWindowState.Normal; this.BringToFront(); // Animate moving up to targetTop over 180 ms int animationDurationMs = 180; int frameIntervalMs = 15; // ~60FPS but can relax int totalFrames = animationDurationMs / frameIntervalMs; for (int frame = 0; frame <= totalFrames; frame++) { if (token.IsCancellationRequested) break; double progress = frame / (double)totalFrames; // ease out cubic double easedProgress = 1 - Math.Pow(1 - progress, 3); int newTop = (int)(workingArea.Bottom + this.Height - ((workingArea.Bottom + this.Height - targetTop) * easedProgress)); Top = newTop; await Task.Delay(frameIntervalMs); } Top = targetTop; BringFormToFront(); textBox1.Focus(); textBox1.Select(); _isAnimating = false; if (token.IsCancellationRequested && !_isVisibleRequested) { // If cancelled and hide requested meanwhile, hide now await AnimateHideAsync(); } } private async Task AnimateHideAsync() { if (InvokeRequired) { await (Task)Invoke(new Func<Task>(AnimateHideAsync)); return; } animationCancellationTokenSource?.Cancel(); animationCancellationTokenSource.Dispose(); animationCancellationTokenSource = new CancellationTokenSource(); _isAnimating = true; var token = animationCancellationTokenSource.Token; var workingArea = Screen.FromControl(this).WorkingArea; int desiredTextBoxScreenY = workingArea.Top + 886; int startTop = this.Top; int hideTop = workingArea.Bottom + this.Height; int animationDurationMs = 180; int frameIntervalMs = 15; int totalFrames = animationDurationMs / frameIntervalMs; for (int frame = 0; frame <= totalFrames; frame++) { if (token.IsCancellationRequested) break; double progress = frame / (double)totalFrames; // ease in cubic double easedProgress = Math.Pow(progress, 3); int newTop = (int)(startTop + (hideTop - startTop) * easedProgress); Top = newTop; await Task.Delay(frameIntervalMs); } Top = hideTop; this.Visible = false; _isAnimating = false; if (token.IsCancellationRequested && _isVisibleRequested) { // If cancelled and show requested meanwhile, show now await AnimateShowAsync(); } } /// <summary> /// Ensures chatbox is foregrounded, focused and ready to receive input /// </summary> public void BringFormToFront() { if (InvokeRequired) { Invoke(new Action(BringFormToFront)); return; } if (!this.Visible) return; var hWnd = this.Handle; if (this.WindowState == FormWindowState.Minimized) { ShowWindow(hWnd, SW_RESTORE); this.WindowState = FormWindowState.Normal; } IntPtr foregroundWindow = GetForegroundWindow(); uint currentThreadId = GetCurrentThreadId(); uint foregroundThreadId = GetWindowThreadProcessId(foregroundWindow, out _); bool attachedThreads = false; if (currentThreadId != foregroundThreadId) { attachedThreads = AttachThreadInput(currentThreadId, foregroundThreadId, true); } SetForegroundWindow(hWnd); if (attachedThreads) { AttachThreadInput(currentThreadId, foregroundThreadId, false); } this.Activate(); this.TopMost = true; this.TopMost = false; textBox1.Focus(); textBox1.Select(); } private async void textBox1_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == (char)Keys.Escape) { e.Handled = true; textBox1.Clear(); await HideChatBoxAsync(); return; } if (e.KeyChar == (char)Keys.Enter) { e.Handled = true; string text = textBox1.Text.Trim(); if (!string.IsNullOrEmpty(text)) { // Only send commands if chatbox fully visible - safety check if (!_isVisibleRequested) { // Ignore inputs if chatbox is hidden/not visible return; } 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 HideChatBoxAsync(); } } } private void timer1_Tick(object sender, EventArgs e) { if (Visible) { // Only bring to front if not animating (optional, can disable if flickering) if (!_isAnimating) { BringFormToFront(); } // Sync colors and background from _form1 textBox1.ForeColor = _form1.textBox3.ForeColor; textBox1.BackColor = _form1.textBox3.BackColor; BackgroundImage = _form1.BackgroundImage; BackgroundImageLayout = _form1.BackgroundImageLayout; } } private void ChatBox_FormClosing(object sender, FormClosingEventArgs e) { animationCancellationTokenSource.Cancel(); animationCancellationTokenSource.Dispose(); } } }
Suggested changes to Form1.cs usage
Replace your existing snippet with:
if (e.VirtualKeyCode == (int)VirtualKeyCode.RETURN) { if (UseChatbox) { if (!chatBox.Visible && !chatBox._isVisibleRequested) { await chatBox.ShowChatBoxAsync(); } else { chatBox.BringFormToFront(); } } }If your event handler is not async, adjust accordingly by changing to:
if (e.VirtualKeyCode == (int)VirtualKeyCode.RETURN) { if (UseChatbox) { if (!chatBox.Visible && !chatBox._isVisibleRequested) { // Fire and forget but avoids blocking UI thread _ = chatBox.ShowChatBoxAsync(); } else { chatBox.BringFormToFront(); } } }
Summary of what this solves:
- The chatbox no longer shows itself instantly while animating. It is marked visible only after animation completes.
- Animation is canceled safely before starting a new one.
- Chatbox cannot be interacted with/receive input while offscreen or animating.
- The form cannot get stuck in invisible but active mode, preventing off-screen speech execution.
- Focus and foreground window handling is improved to reduce focus loss or failure to focus issues.
HideChatBoxAsync()is used consistently to animate hiding properly.
Try this improved code to greatly reduce the possibility of the chatbox hanging, off-screen commands firing, or getting stuck.
If you want, I can also suggest or help with potential UI logic (e.g., making sure the chatbox cancels animation on quick show/hide toggling).
Let me know if you want me to help add that.