问题描述
在我的应用程序中,我尝试着眼于文本框,以便可以在加载表单后立即键入内容.
当显示 Form
时,我可以看到光标在 TextBox
中闪烁,但是如果输入内容,则什么也没有发生.
我需要单击窗口以开始在 TextBox
中输入文本.如果我从Visual Studio中正常运行我的应用程序,它将可以正常运行,但是如果我的应用程序是使用Task Scheduler运行的,则会发生这种情况.
你有什么建议吗?
In my appplication I am trying to focus a textbox so I can type straight away after the Form is loaded.
When the Form
is shown, I can see is the cursor blinking in the TextBox
but if I type something nothing happens.
I need to click the Window to start entering text in the TextBox
. If I run my application normally from Visual Studio, it will work perfectly, but if my application is run using the Task Scheduler, then this happens.
Do you have any advice?
下面是我的代码:
this.TopMost = true;
textbox.Focus();
我也尝试了 textbox.Select();
,但是它仍然无法正常工作.
I also tried textbox.Select();
but it doesn't work anyway.
推荐答案
问题:当应用程序由任务计划程序操作"运行时,主窗口显示为非活动状态,系统通知用户在屏幕上闪烁应用程序的图标任务栏.这是设计.
The problem: when the application is run by a Task Scheduler Action, the main Window is shown non-active and the System notifies the User flashing the application's icon in the Task Bar. This is by design.
一个简单的解决方法是设置启动窗口的 WindowState
=
FormWindowState.Minimized
,然后将其设置回 FormWindowState.Normal
>在Window完成加载其内容并准备好显示之后,请提起已显示事件.
A simple workaround is to set the startup Window's WindowState
=
FormWindowState.Minimized
in the Form Designer, then set it back to FormWindowState.Normal
after the Window has completed loading its content and it's ready to be presented, raising the Shown event.
设置 FormWindowState.Normal
导致呼叫到 ShowWindow ,其中 nCmdShow
设置为 SW_SHOWNORMAL
:
Setting FormWindowState.Normal
causes a call to ShowWindow with nCmdShow
set to SW_SHOWNORMAL
:
窗口现在将正常显示,处于活动状态并准备接收输入.
此外,代码使用 ActiveControl 属性.
The Window is now shown as usual, active and ready to receive input.
Also, the code sets explicitly the Control that should receive the input, using the ActiveControl property.
我建议使 Shown
处理程序 async
并在重新设置 WindowState
属性之前添加一个小的延迟,以防止任务栏图标不会陷入闪烁状态.
I suggested to make the Shown
handler async
and add a small delay before re-setting the WindowState
property, to prevent the Task Bar icon from getting stuck in a blinking state.
如果需要重新定位或调整窗口的大小,则需要在重置 WindowState
之后执行此操作,因为在此之前,窗口处于最小化状态,并且不会缓存位置的大小值.
应该设置表单的 StartPosition 到 FormStartPosition.Manual
If the Window needs to be repositioned or resized, this needs to be done after the WindowState
has been reset, since the Window is in a minimized state before that and won't cache position an size values.
The Form's StartPosition should be set to FormStartPosition.Manual
private async void MainForm_Shown(object sender, EventArgs e)
{
await Task.Delay(500);
this.WindowState = FormWindowState.Normal;
this.ActiveControl = [A Control to activate];
}
这篇关于从任务计划程序运行应用程序时未激活窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!