[英]How to prevent my C# winforms application from stealing focus when I set the visible properly to true?
[英]How do I set the focus to the Desktop from within my C# application
Winforms應用程序。 .Net 3.5。
我需要將焦點從我的C#應用程序設置到用戶的桌面(幾乎就像在桌面上模擬鼠標單擊一樣)。
有人可以告訴我如何使用C#嗎? 我只想將焦點放在桌面上,因此焦點不再放在我的應用程序上,而是要在我的應用程序內執行此操作。
編輯:下面的答案通過將焦點設置在桌面上而起作用,但是它最小化了用戶桌面上所有打開的窗口。
有什么方法可以將焦點設置為桌面上的下一個打開的窗口嗎? 我只想將重點轉移到我的應用程序上(而不是最小化或隱藏應用程序)。 我只想將重點轉移到其他地方。 如果它將最小化所有用戶打開的窗口/應用程序,則桌面不是最佳選擇。
這應該為您做。
using System;
using System.Runtime.InteropServices;
namespace ConsoleApplication1 {
class Program {
[DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll", EntryPoint = "SendMessage", SetLastError = true)]
static extern IntPtr SendMessage(IntPtr hWnd, Int32 Msg, IntPtr wParam, IntPtr lParam);
const int WM_COMMAND = 0x111;
const int MIN_ALL = 419;
const int MIN_ALL_UNDO = 416;
static void Main(string[] args) {
IntPtr lHwnd = FindWindow("Shell_TrayWnd", null);
SendMessage(lHwnd, WM_COMMAND, (IntPtr)MIN_ALL, IntPtr.Zero);
System.Threading.Thread.Sleep(2000);
SendMessage(lHwnd, WM_COMMAND, (IntPtr)MIN_ALL_UNDO, IntPtr.Zero);
}
}
}
我沒有針對這兩個代碼的示例,但我將為您提供兩者的鏈接。 您首先需要做的就是調用GetWindow
。 完成之后,您將要調用SwitchToThisWindow
並傳入從GetWindow
收到的指針。
您可以在項目中添加此COM對象:
Microsoft Shell控件和自動化
然后只需調用:
Shell32.ShellClass shell = new Shell32.ShellClass();
shell.MinimizeAll();
這將最小化所有窗口,然后將焦點放在桌面上。 否則,如果窗口非全屏顯示,則可以使用以下方法模擬鼠標單擊:
//This is a replacement for Cursor.Position in WinForms
[System.Runtime.InteropServices.DllImport("user32.dll")]
static extern bool SetCursorPos(int x, int y);
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);
public const int MOUSEEVENTF_LEFTDOWN = 0x02;
public const int MOUSEEVENTF_LEFTUP = 0x04;
//This simulates a left mouse click
public static void LeftMouseClick(int xpos, int ypos)
{
SetCursorPos(xpos, ypos);
mouse_event(MOUSEEVENTF_LEFTDOWN, xpos, ypos, 0, 0);
mouse_event(MOUSEEVENTF_LEFTUP, xpos, ypos, 0, 0);
}
您可以通過查看窗口的啟動位置加上高度/寬度並選擇一個可用空間(實際上就是桌面)來計算坐標。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.