gpt4 book ai didi

C# 强制表单焦点

转载 作者:IT王子 更新时间:2023-10-29 04:29:51 25 4
gpt4 key购买 nike

所以,在问这个问题之前,我确实搜索了 google 和 SO。基本上我有一个 DLL,其中编译了一个表单。该表单将用于在屏幕上显示信息。最终它将是异步的,并在 dll 中公开大量自定义。现在我只想让它正确显示。我遇到的问题是我通过在 Powershell session 中加载它来使用 dll。因此,当我尝试显示表单并将其置于顶部并获得焦点时,显示所有其他应用程序没有问题,但我终生无法让它显示在 Powershell 窗口上.这是我目前用来尝试让它显示的代码。我敢肯定,一旦我弄明白了,就不需要其中的大部分内容,这只代表了我通过 google 找到的所有内容。

CLass Blah
{
[DllImport("user32.dll", EntryPoint = "SystemParametersInfo")]
public static extern bool SystemParametersInfo(uint uiAction, uint uiParam, uint pvParam, uint fWinIni);

[DllImport("user32.dll", EntryPoint = "SetForegroundWindow")]
public static extern bool SetForegroundWindow(IntPtr hWnd);

[DllImport("User32.dll", EntryPoint = "ShowWindowAsync")]
private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
private const int WS_SHOWNORMAL = 1;

public void ShowMessage(string msg)
{
MessageForm msgFrm = new MessageForm();
msgFrm.lblMessage.Text = "FOO";
msgFrm.ShowDialog();
msgFrm.BringToFront();
msgFrm.TopMost = true;
msgFrm.Activate();

SystemParametersInfo((uint)0x2001, 0, 0, 0x0002 | 0x0001);
ShowWindowAsync(msgFrm.Handle, WS_SHOWNORMAL);
SetForegroundWindow(msgFrm.Handle);
SystemParametersInfo((uint)0x2001, 200000, 200000, 0x0002 | 0x0001);
}
}

正如我所说,我确信其中大部分要么不需要,要么完全错误,我只是想展示我尝试过的东西。另外,正如我提到的,我计划在某个时候异步显示它,我怀疑最终需要一个单独的线程。将表单拆分到它自己的线程中会更容易使其专注于 Powershell session 吗?


@Joel,感谢您提供信息。这是我根据您的建议尝试的方法:

msgFrm.ShowDialog();
msgFrm.BringToFront();
msgFrm.Focus();
Application.DoEvents();

该表单仍然出现在 Powershell session 。我将继续处理线程。我以前生成过线程,但从来没有在父线程需要与子线程对话的地方生成过,所以我们将看看它是如何进行的。

感谢大家到目前为止提出的所有想法。


好的,线程处理解决了这个问题。 @Quarrelsome,我确实尝试了这两种方法。都没有(也没有一起)工作。我很好奇使用线程有什么坏处?我没有使用 Application.Run,​​我还没有遇到问题。我正在使用父线程和子线程都可以访问的中介类。在该对象中,我使用 ReaderWriterLock 来锁定一个属性,该属性表示我希望在子线程创建的表单上显示的消息。父级锁定属性然后写入应显示的内容。子线程锁定该属性并读取它应该将表单上的标签更改为什么。 child 必须在轮询间隔(我默认为 500 毫秒)执行此操作,我对此并不满意,但我找不到事件驱动的方式让子线程知道属性已更改,所以我'我坚持投票。

最佳答案

我在激活窗口并将窗口调到前台时也遇到了问题。这是最终为我工作的代码。我不确定它是否能解决您的问题。

基本上,先调用 ShowWindow(),然后调用 SetForegroundWindow()。

using System.Diagnostics;
using System.Runtime.InteropServices;

// Sets the window to be foreground
[DllImport("User32")]
private static extern int SetForegroundWindow(IntPtr hwnd);

// Activate or minimize a window
[DllImportAttribute("User32.DLL")]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
private const int SW_SHOW = 5;
private const int SW_MINIMIZE = 6;
private const int SW_RESTORE = 9;

private void ActivateApplication(string briefAppName)
{
Process[] procList = Process.GetProcessesByName(briefAppName);

if (procList.Length > 0)
{
ShowWindow(procList[0].MainWindowHandle, SW_RESTORE);
SetForegroundWindow(procList[0].MainWindowHandle);
}
}

关于C# 强制表单焦点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46030/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com