c#基于Win32Api实现返回Windows桌面功能
// Wpf主窗口
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
InitLogger();
InitUdpThread();
showDesktop = Method1;
Logger.LogMessage(Severity.Info, $"start process, Main Thread id: {Thread.CurrentThread.ManagedThreadId}");
}
private void InitLogger()
{
var file = new FileLogger("log.txt");
Logger.LogMessage(Severity.Info, "Init logger success");
}
private void InitUdpThread()
{
Thread udpThread = new Thread(new ThreadStart(GetUdpMessage));
udpThread.IsBackground = true;
udpThread.Start();
}
private void GetUdpMessage()
{
UdpClient udpClient = null;
try
{
udpClient = new UdpClient(10001);
}
catch (Exception)
{
Logger.LogMessage(Severity.Error, "create udp client failed");
return;
}
Logger.LogMessage(Severity.Info, "create udp client success");
IPEndPoint remotePoint = null;
while (true)
{
try
{
byte[] receiveData = udpClient.Receive(ref remotePoint);
string receiveString = Encoding.Default.GetString(receiveData);
Logger.LogMessage(Severity.Info, $"receive udp message: {receiveString}");
if (receiveString.ToLower().Contains("showdesktop"))
showDesktop?.Invoke();
}
catch (Exception e)
{
Logger.LogMessage(Severity.Error, e.Message);
}
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
if (sender is Button btn)
{
switch (btn.Name)
{
case "method1":
showDesktop = Method1;
Logger.LogMessage(Severity.Info, "turn to method1");
break;
case "method2":
showDesktop = Method2;
Logger.LogMessage(Severity.Info, "turn to method2");
break;
case "activeFirst":
showDesktop = ActiveFirst;
Logger.LogMessage(Severity.Info, "turn to activeFirst method");
break;
default:
break;
}
}
}
private void Method1()
{
Thread newSta = new Thread(()=>
{
Shell32.ShellClass objShel = new Shell32.ShellClass();
objShel.ToggleDesktop();
Logger.LogMessage(Severity.Info, $"Current Thread id: {Thread.CurrentThread.ManagedThreadId}");
});
newSta.TrySetApartmentState(ApartmentState.STA);
newSta.Start();
}
private void Method2()
{
Type shellType = Type.GetTypeFromProgID("Shell.Application");
object shellObject = System.Activator.CreateInstance(shellType);
shellType.InvokeMember("ToggleDesktop", System.Reflection.BindingFlags.InvokeMethod, null, shellObject, null);
Logger.LogMessage(Severity.Info, $"Current Thread id: {Thread.CurrentThread.ManagedThreadId}");
}
private void ActiveFirst()
{
App.Current.Dispatcher.Invoke(new Action(() =>
{
Win32Api.SetWindowToForegroundWithAttachThreadInput(this);
Method2();
}));
}
private Action showDesktop;
}
- .NET Core系列之MemoryCache 初识
- 007手机一键Root(安机网一键Root) v3.0 官方最新版 一键ROOT您的Android手机
- 12306密码被盗了怎么办?12306密码外泄解决方法
- 12个字的qq网名
- 150M迷你型无线路由器怎么设置?
- 192.168.1.1打不开怎么办?路由器192.168.1.1打不开的原因以及解决办法
- 2011年电子报合订本 电子报 编辑部 中文 PDF版 [84M]
- 2015年1月15日小米新旗舰发布会现场图文直播
- 2016.3.1vivo Xplay5新品发布会现场视频直播 优酷直播
- 2016华为P9发布会视频直播地址 4月15日华为P9国行发布会直播