0

我知道已经有一些关于这个的话题了。如果我单击记事本或任何程序,它不会在其中输入任何数据,而只会在我的 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 时才能正常工作,这是 Visual Studio 托管进程。我在设置中禁用了它,当我从 VS 启动时它工作正常但是当我只运行 bin 文件夹中的 exe 时,我仍然得到奇怪的结果

编辑

这是我用我的结果制作的快速视频http://www.youtube.com/watch?v=1ozpHSRGnMo

新编辑

我为解决这个问题所做的就是通过这样做将我的应用程序设置为全屏模式,这样用户就可以在不先关闭这个窗口的情况下点击其他窗口

this.FormBorderStyle = FormBorderStyle.None;
this.WindowState = FormWindowState.Maximized;
4

3 回答 3

5

确实,您无法阻止其他窗口获得焦点,但是您可以在它们获得焦点的第二秒从它们那里获得焦点;)

private void timer1_Tick(object sender, EventArgs e)
{
    if (!this.Focused)
    {
        this.Activate();
    }
}

只需创建一个计时器,从一开始就启用它,使滴答间隔尽可能小,并将上面的代码作为滴答事件。

希望这可以帮助

对不起英语不好

于 2013-04-07T17:10:08.580 回答
1

您的代码看起来不错,应该可以正常工作,您可以尝试以下 URL 中建议的内容吗...不过只是一个建议,而不是使用

this.TopMost = true;

http://www.c-sharpcorner.com/uploadfile/kirtan007/make-form-stay-always-on-top-of-every-window/

于 2013-03-19T22:43:26.997 回答
0

您不能创建可以阻止其他程序获得焦点的 Windows 窗体应用程序。Windows 本身不允许这样做。解决此问题的唯一方法是在全屏模式下创建一个OpenGL或应用程序。DirectX这将阻止用户查看任何其他应用程序。但即使这样,用户也可以Alt+Tab返回到其他应用程序。

于 2013-03-20T06:51:08.597 回答