SetWindowLong 设置外部窗体始终是激活状态
时间: 2024-02-19 15:59:28 浏览: 21
如果使用`SetWindowLong`函数将外部窗体样式设置为`WS_EX_NOACTIVATE`后,仍然不能达到不激活窗体的效果,可能是因为该窗体是以管理员权限运行的,而你的程序没有管理员权限。
解决方法是在程序启动时,以管理员权限运行。具体方式是右键点击程序图标,选择“以管理员身份运行”。
如果你想在程序运行时自动获取管理员权限,可以在程序的`app.manifest`文件中添加以下代码:
```xml
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
```
这样,在程序运行时,如果没有管理员权限,系统会自动提示用户授予管理员权限。
相关问题
C# 去掉外部程序的窗体激活状态监听
要去除外部程序的窗体激活状态监听,可以使用`SetWindowLong`函数来修改窗口样式。具体步骤如下:
1. 首先,需要引入Win32 API函数:
```csharp
[DllImport("user32.dll")]
public static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
```
2. 然后,在启动外部程序前,需要获取该程序的窗口句柄:
```csharp
Process process = new Process();
process.StartInfo.FileName = "path/to/your/program.exe";
process.Start();
process.WaitForInputIdle();
IntPtr hWnd = process.MainWindowHandle;
```
这里使用`process.MainWindowHandle`获取外部程序的主窗口句柄。
3. 最后,使用`SetWindowLong`函数来修改窗口样式:
```csharp
const int GWL_EXSTYLE = -20;
const int WS_EX_NOACTIVATE = 0x08000000;
int style = GetWindowLong(hWnd, GWL_EXSTYLE);
SetWindowLong(hWnd, GWL_EXSTYLE, style | WS_EX_NOACTIVATE);
```
在这个示例中,我们使用`SetWindowLong`函数将窗口样式修改为`WS_EX_NOACTIVATE`,这样程序窗口就不会被激活。
完整代码如下:
```csharp
using System.Diagnostics;
using System.Runtime.InteropServices;
[DllImport("user32.dll")]
public static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
[DllImport("user32.dll")]
public static extern int GetWindowLong(IntPtr hWnd, int nIndex);
const int GWL_EXSTYLE = -20;
const int WS_EX_NOACTIVATE = 0x08000000;
Process process = new Process();
process.StartInfo.FileName = "path/to/your/program.exe";
process.Start();
process.WaitForInputIdle();
IntPtr hWnd = process.MainWindowHandle;
int style = GetWindowLong(hWnd, GWL_EXSTYLE);
SetWindowLong(hWnd, GWL_EXSTYLE, style | WS_EX_NOACTIVATE);
```
在这个示例中,我们使用了`GetWindowLong`函数来获取窗口原有的样式,然后使用`SetWindowLong`函数将其修改为`WS_EX_NOACTIVATE`。
SetWindowLong 设置为WS_EX_ACTIVE
如果使用`SetWindowLong`函数将外部窗体样式设置为`WS_EX_ACTIVE`,则会使窗口始终处于激活状态,即使用户切换到其他窗口,该窗口也会保持在最前面。这可能会影响用户的操作体验,所以不建议这样做。
如果你想让窗口在用户切换到其他窗口时失去焦点,可以使用`SetForegroundWindow`函数,将焦点设置到其他窗口上。具体方式如下:
```csharp
[DllImport("user32.dll")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
Process process = new Process();
process.StartInfo.FileName = "path/to/your/program.exe";
process.Start();
process.WaitForInputIdle();
IntPtr hWnd = process.MainWindowHandle;
SetForegroundWindow(hWnd);
```
在这个示例中,我们使用`SetForegroundWindow`函数将焦点设置到外部程序的窗口上,这样就可以在用户切换到其他窗口时使该窗口失去焦点。