如何从我的 C# 应用程序中将焦点设置到桌面 [英] How do I set the focus to the Desktop from within my C# application

查看:51
本文介绍了如何从我的 C# 应用程序中将焦点设置到桌面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Winforms 应用程序..Net 3.5.

Winforms App. .Net 3.5.

我需要将焦点从我的 C# 应用程序设置到用户的桌面(几乎就像在桌面上模拟鼠标点击一样).

I need to set the focus from my C# application to the user's desktop (almost like simulating a mouse click on the desktop).

有人可以告诉我如何用 C# 做到这一点吗?我只想将焦点设置在桌面上,因此焦点不再放在我的应用程序上,但我想在我的应用程序中执行此操作.

Can someone please show me how to do this with C#? I just want to set focus on the desktop so the focus is no longer on my application but I want to do this from within my application.

下面的答案通过将焦点设置到桌面来工作,但它会最小化用户桌面上所有打开的窗口.

An answer below works by setting the focus to the desktop, but it minimizes all the open windows on the user's desktop.

有没有办法可以将焦点设置到桌面上的下一个打开的窗口?我只是想把注意力从我的应用程序上移开(而不是最小化我的应用程序或隐藏它).我只是想将注意力转移到其他地方.如果桌面将最小化用户打开的所有窗口/应用程序,那么它可能不是最佳选择.

Is there a way I can maybe set the focus to the next open window on the desktop instead? I just want to get the focus off of my application (without minimizing my application or hiding it). I just want to move focus to somewhere else. Maybe the desktop was not the best choice if it will minimize all the user's open windows/applications.

推荐答案

你可以在你的项目中添加这个 COM 对象:

You can add this COM object in your project:

Microsoft Shell 控件和自动化

然后调用:

Shell32.ShellClass shell = new Shell32.ShellClass();
shell.MinimizeAll();

这将最小化所有窗口,然后聚焦桌面.否则,如果您的窗口不是全屏,那么您可以使用以下方法模拟鼠标点击:

This will minimize all the windows and then focus the desktop. Otherwise, if you have your window non-full screen then you can simulate the mouse click using:

//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);
}

您可以通过查看窗口启动位置加上高度/宽度并选择一个可用空间(实际上就是桌面)来计算坐标.

You can calculate coordinates by looking at your window startup location plus height/width and select a available space (that will be the desktop indeed).

这篇关于如何从我的 C# 应用程序中将焦点设置到桌面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆