【发布时间】:2013-03-19 07:28:52
【问题描述】:
我知道已经有一些关于此的主题。如果我单击记事本或任何程序,它不会在其中输入任何数据,而只会在我的 Windows 窗体文本框中输入数据,那么我需要的是让 Windows 窗体窗口始终集中含义。
我发现这段代码可以解释更多
//Delegates for safe multi-threading.
delegate void DelegateGetFocus();
private DelegateGetFocus m_getFocus;
Thread newThread;
public MemberLogin()
{
m_getFocus = new DelegateGetFocus(this.getFocus);
InitializeComponent();
spawnThread(keepFocus);
toggleFocusButton.Text = "OFF";
timer1.Interval = 2000;
textBox1.Select();
}
//test focus stuff
//Spawns a new Thread.
private void spawnThread(ThreadStart ts)
{
try
{
newThread = new Thread(ts);
newThread.Start();
}
catch (Exception e)
{
MessageBox.Show(e.Message, "Exception!", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
//Continuously call getFocus.
private void keepFocus()
{
while (true)
{
getFocus();
}
}
//Keeps Form on top and gives focus.
private void getFocus()
{
//If we need to invoke this call from another thread.
if (this.InvokeRequired)
{
this.Invoke(m_getFocus, new object[] { });
}
//Otherwise, we're safe.
else
{
//having this seemed to have kept my windows onTop at all times even when off
// this.TopMost = true;
this.TopMost = true;
this.Activate();
this.textBox1.Select();
this.textBox1.Focus();
}
}
此代码似乎仅在我的项目打开时才能正常工作,这意味着当我的 Visual Studio 项目关闭时,窗口位于最顶部但没有焦点,这意味着我可以在其他程序中键入。我发现奇怪的是,记事本和我的文本框都有闪烁的线条,告诉你在哪里写文本。如果我从 Visual Studio 项目运行我的应用程序,一切正常,当我尝试单击其他窗口时,它不会让我访问我想要的。
所以我有点困惑,为什么它只在打开项目的情况下才能正常工作
还请注意,只要打开项目,即使 .exe 和我制作的其他副本也能正常工作,我会关闭项目解决方案,程序会按照我上面解释的方式执行。
刚刚做了一些测试,它似乎只有在这个进程运行 vhost.exe 时才能正常工作,vhost.exe 是 Visual Studio 托管进程。我在设置中禁用了它,当我从 VS 启动时它工作正常,但是当我只运行 bin 文件夹中的 exe 时,我仍然得到奇怪的结果
编辑
这是我用我的结果制作的快速视频http://www.youtube.com/watch?v=1ozpHSRGnMo
新编辑
我解决这个问题的方法是将我的应用程序设置为全屏模式,这样用户就可以在不先关闭这个窗口的情况下点击其他窗口
this.FormBorderStyle = FormBorderStyle.None;
this.WindowState = FormWindowState.Maximized;
【问题讨论】:
-
Windows 有明确的对策来阻止您这样做。程序员从不考虑明显的故障模式:如果 两个 程序会这样做呢?
-
查看我刚刚制作的显示结果的视频youtube.com/watch?v=1ozpHSRGnMo,不,它不是重复的,因为我说代码有效,我从本网站的另一篇文章中得到它。但是该代码仅在从 VS2012 执行时才有效,这意味着当我按下 F5 按钮运行我的应用程序时。就像我什至不能点击其他窗口一样,这就是我想要的!但是然后我运行exe,我可以在记事本等其他windows中编写。所以我的想法是 VS2012 以某种方式让我的应用程序比其他应用程序更优先。
标签: c# .net winforms window form-control