using Container.Business;
using Container.ChildWindows;
using Container.Common;
using Container.Control;
using Container.Model;
using Container.Services;
using Container.Win;
using Microsoft.Win32;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
//using System.Runtime.InteropServices;
using System.Windows.Threading;
using Transitionals;
namespace Container
{
///
/// MainWindow.xaml 的交互逻辑
///
public partial class MainWindow : Window
{
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string IpClassName, string IpWindowName);
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr SetParent(IntPtr ChildWin, IntPtr FatherWin);
[DllImport("user32.dll", SetLastError = true)]
static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, uint uflags);
[DllImport("user32.dll", SetLastError = true)]
static extern bool MoveWindow(IntPtr hWnd, int x, int y, int nWindth, int nheight, bool brepaint);
DispatcherTimer timer = new DispatcherTimer();
DispatcherTimer timerRecord = new DispatcherTimer();
//DispatcherTimer timerDownFiles = new DispatcherTimer();
BackgroundWorker background = new BackgroundWorker();//主线程
private Class_Log log = new Class_Log(); //日志记录文件
private bool isStop = false;//是否关闭线程
private string shutDownTime = string.Empty;//记录上一次获取的关机时间
private Thread HeatBeatThread;//获取关机指令的心跳线程
HttpMessage httpmessage = new HttpMessage(); //通讯类
App app = ((App)System.Windows.Application.Current);
Class_Config config = new Class_Config(); //加载配置文件
List MyProcessName = new List(); //当前打开的应用程序进程名
WebSocketManage web = new WebSocketManage();
BackgroundWorker backgroundWorker;
bool startexe = false;
const int WM_CLOSE = 0x0010;//关闭窗体
PlayBackManage pbm = new PlayBackManage();
private const uint WM_SYSCOMMAND = 0x112; //系统消息
private const int SC_MONITORPOWER = 0xF020; //关闭显示器的系统命令
private const int SC_SCREENSAVE = 0xf140;
private const int MonitorPowerOff = 2; //2为PowerOff, 1为省电状态,-1为开机
private const int MonitorPowerOn = -1; //2为PowerOff, 1为省电状态,-1为开机
private static readonly IntPtr HWND_BROADCAST = new IntPtr(0xffff);//广播消息,所有顶级窗体都会接收
private Socket socket;
[DllImport("user32.dll")]
static extern void mouse_event(MouseEventFlag flags, int dx, int dy, int data, UIntPtr extraInfo);
[Flags]
enum MouseEventFlag : uint
{
Move = 0x0001,
LeftDown = 0x0002,
LeftUp = 0x0004,
RightDown = 0x0008,
RightUp = 0x0010,
MiddleDown = 0x0020,
MiddleUp = 0x0040,
XDown = 0x0080,
XUp = 0x0100,
Wheel = 0x0800,
VirtualDesk = 0x4000,
Absolute = 0x8000
}
public WindowViewNew WinView
{
set
{
if (value != null)
{
log.WriteLogFile("main关了", "seeyou");
value.Close();
Thread.Sleep(2500);
//Process[] pro = Process.GetProcesses();
//for (int i = 0; i < pro.Length; i++)
//{
// if (pro[i].ProcessName.ToLower() == "pcscreensavers.exe")
// {
// pro[i].Kill();//结束进程
// return;
// }
//}
timer_Tick("", new EventArgs());
log.WriteLogFile("结束", "seeyou");
}
}
}
public MainWindow()
{
InitializeComponent();
//判断是否已经打开了改程序,防止重复打开
string Productname = System.Windows.Forms.Application.ProductName;
Process[] p = Process.GetProcessesByName(Productname);
if (p.Length > 1)
{
Environment.Exit(0);
}
app.ScreenWidth = SystemParameters.PrimaryScreenWidth;
app.ScreenWidth = 1920;
app.ScreenHeight = SystemParameters.PrimaryScreenHeight;
app.ScreenHeight = 1080;
config.LoadConfig();
this.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
backgroundWorker = new BackgroundWorker();
backgroundWorker.WorkerReportsProgress = true;
backgroundWorker.WorkerSupportsCancellation = true;
backgroundWorker.ProgressChanged += BackgroundWorker_ProgressChanged;
backgroundWorker.RunWorkerCompleted += BackgroundWorker_RunWorkerCompleted;
backgroundWorker.DoWork += BackgroundWorker_DoWork;
timer.Tick += new EventHandler(timer_Tick);
timer.Interval = TimeSpan.FromSeconds(60);
//timerDownFiles.Tick += new EventHandler(timerDownFiles_Tick);
//timerDownFiles.Interval = TimeSpan.FromHours(1);
app.kioskUrl = ConfigurationManager.AppSettings["kioskUrl"];
app.OBSPath = ConfigurationManager.AppSettings["OBSPath"];
mLastInputInfo = new LASTINPUTINFO();
mLastInputInfo.cbSize = Marshal.SizeOf(mLastInputInfo);
//if (ConfigurationManager.AppSettings["isOnlyScreensaver"].Equals("1"))
//{
//mIdleTimer = new System.Windows.Threading.DispatcherTimer();
//mIdleTimer.Tick += new EventHandler(IdleTime);//起个Timer一直获取当前时间
//mIdleTimer.Interval = new TimeSpan(0, 0, 0, 1, 0);
WebSocketManageForLive.WebSocketReceiveEvent += new WebSocketManageForLive.WebSocketReceiveDelegate(WebSocketManageForLive_WebSocketReceiveEvent);
WebsocketForVoice websocketForVoice = new WebsocketForVoice();
websocketForVoice.openSocket();
StartSocketServer();
KillExplorer();
WebSocketForKiosk webSocketForKiosk = new WebSocketForKiosk();
webSocketForKiosk.openSocket();
//}
//ChatWebSocketMiddleware chatWebSocketMiddleware = new ChatWebSocketMiddleware();
//chatWebSocketMiddleware.openSocket();
//SocketService socketService = new SocketService();
//socketService.openSocket();
}
private void StartSocketServer()
{
try
{
IPAddress ip = IPAddress.Parse("127.0.0.1");
//当开始监听时候,在服务器创建一个负责IP地址跟端口号的Socket
Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint point = new IPEndPoint(ip, 8000);
//监听
socketWatch.Bind(point);
socketWatch.Listen(10);
Thread th = new Thread(ListenClickConnect);
th.IsBackground = true;
th.Start(socketWatch);
}
catch { }
}
public void ListenClickConnect(object o)
{
Socket socketWatch = o as Socket;
//等待用户连接创建一个负责通信的Socket
while (true)
{
try
{
socket = socketWatch.Accept();//等到客户端新的连接
}
catch
{
}
}
}
void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
//BackgroundWorker worker = sender as BackgroundWorker;
//try
//{
// bool done = false;
// int port = int.Parse(app.configport);
// System.Net.IPAddress localIP = System.Net.IPAddress.Parse("127.0.0.1");
// TcpListener listener = new TcpListener(localIP, port);
// listener.Start();//开始监听。。
// while (!done)
// {
// TcpClient tc = listener.AcceptTcpClient();
// log.WriteLogFile("Connection Accepted:" + tc.Client.RemoteEndPoint.ToString(), "TCPLog");
// NetworkStream ns = tc.GetStream();
// try
// {
// int BufferSize = 1024;
// byte[] buffer = new byte[BufferSize];
// lock (ns)
// {
// try
// {
// int bytesRead = ns.Read(buffer, 0, BufferSize);//获取客户端的数据
// System.Text.UTF8Encoding ASCII = new System.Text.UTF8Encoding();
// string Messages = ASCII.GetString(buffer).Substring(0, bytesRead);//字节数组转成字符串
// log.WriteLogFile(ASCII.GetString(buffer).Substring(0, bytesRead), "TCPLog");
// if (Messages.Trim().Equals("0"))
// {
// worker.ReportProgress(1, null);
// }
// else
// {
// string[] str = Messages.Split('|');
// if (str.Count() > 1)
// {
// if (str.Count() == 2)
// {
// app.Appversion = str[0].Trim().Replace("\u0000", "");
// app.AppPlayNameCH = str[1].Trim().Replace("\u0000", "");
// }
// else if (str.Count() == 3)
// {
// app.Appversion = "v" + str[2].Trim().Replace("\u0000", "");//.Replace("\u0000", "")
// app.AppPlayNameCH = str[1].Trim().Replace("\u0000", "");
// }
// }
// else
// {
// if (Messages.Trim().Replace("\u0000", "").Length < 8)
// app.Appversion = Messages.Trim();
// if (app.AppPlayName.ToLower().Contains("pc"))
// app.AppPlayNameCH = "信息发布";
// else
// app.AppPlayNameCH = "导视";
// }
// worker.ReportProgress(0, null);
// }
// }
// catch (Exception ex)
// {
// log.WriteLogFile(ex.ToString(), "TCPLog");
// //worker.ReportProgress(2, null);
// }
// Thread.Sleep(5000);
// }
// ns.Close();
// tc.Close();
// }
// catch (Exception ex)
// {
// log.WriteLogFile(ex.ToString(), "TCPLog");
// }
// }
//}
//catch (Exception ex)
//{
// log.WriteLogFile(ex.ToString(), "TCPLog");
// worker.ReportProgress(2, null);
//}
//e.Cancel = true;
return;
}
void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
}
void BackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
int progressPercentage = e.ProgressPercentage;
string userState = (string)e.UserState;
try
{
switch (progressPercentage)
{
case 0:
//收到数据事件
timer.Start();
break;
case 1:
app.AppPlayName = "";
app.CurAppPlayName = app.AppPlayName;
app.NowAppType = "";
//MessageBox.Show("TCP服务启动失败");
timer.Stop();
break;
case 2:
//MessageBox.Show("TCP服务启动失败");
//this.Close();
background.CancelAsync();
break;
default: break;
}
}
catch (System.Exception)
{
}
}
[DllImport("kernel32.dll", EntryPoint = "SetProcessWorkingSetSize")]
public static extern int SetProcessWorkingSetSize(IntPtr process, int minSize, int maxSize);
private void timer_Tick(object sender, EventArgs e)
{
try
{
Process[] pro = Process.GetProcesses();
//if (app.AppList.Count > 0)
//{
// var needApp = app.AppTimeList.Where(i => i.BeginTimeSlot.Substring(0, 2) == DateTime.Now.ToString("HH")).Join(app.AppList, at => at.AppCode, al => al.Code, (at, al) => al).FirstOrDefault();
// if (needApp == null)
// {
// var defaultApp = app.AppList.Where(i => i.Default == bool.TrueString).FirstOrDefault();
// if (app.NowNeedPlayApp == null || app.NowNeedPlayApp.Name != defaultApp.Name)
// {
// app.NowNeedPlayApp = defaultApp;
// }
// }
// else
// {
// if (app.NowNeedPlayApp == null || app.NowNeedPlayApp.Name != needApp.Name)
// {
// app.NowNeedPlayApp = needApp;
// }
// }
// bool pcstart = false;
// //for (int i = 0; i < pro.Length; i++)
// //{
// // if (pro[i].ProcessName.ToLower().Trim() == "pcscreensavers")
// // {
// // pcstart = true;
// // }
// //}
// IntPtr Win = FindWindow(null, "WindowViewNew");//设置置顶
// if (Win != null && Win != IntPtr.Zero)
// {
// pcstart = true;
// //SetWindowPos(Win, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
// }
// if (pcstart)
// {
// if (app.AppPlayinfo == null || app.AppPlayinfo.Name != app.NowNeedPlayApp.Name)
// {
// app.AppPlayinfo = app.NowNeedPlayApp;
// ChangeExE(app.NowNeedPlayApp.Startup, (app.HttpUrl.Replace("//", "|")).Split('/')[0].Replace("|", "//") + "|" + app.deviceid + "|" + app.configwebsocket + "|");
// return;
// }
// }
//}
#region 注释用于测试
if (app.AppList.Count > 0)
{
var needApp = app.AppTimeList.Where(i => i.BeginTimeSlot.Substring(0, 2) == DateTime.Now.ToString("HH")).Join(app.AppList, at => at.AppCode, al => al.Code, (at, al) => al).FirstOrDefault();
if (needApp == null)
{
var defaultApp = app.AppList.Where(i => i.Default == bool.TrueString).FirstOrDefault();
app.NowNeedPlayApp = defaultApp;
}
else
{
app.NowNeedPlayApp = needApp;
}
}
string palyExe = string.Empty;
if (app.NowNeedPlayApp == null)
{
app.AppPlayinfo = null;
palyExe = app.configstartexe;
}
else
{
app.AppPlayinfo = app.NowNeedPlayApp;
palyExe = app.NowNeedPlayApp.Startup;
}
if (!string.IsNullOrEmpty(palyExe))
{
bool pcstart = false;
IntPtr Win = FindWindow(null, "WindowViewNew");//设置置顶
if (Win != null && Win != IntPtr.Zero)
{
pcstart = true;
SetWindowPos(Win, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
}
bool kioskStart = false;
bool chromeStart = false;
for (int i = 0; i < pro.Length; i++)
{
if (pro[i].ProcessName.ToLower() == app.AppPlayName.ToLower())
{
kioskStart = true;
break;
}
if (pro[i].ProcessName.ToLower() == "chrome")
{
chromeStart = true;
break;
}
}
if (!(kioskStart || (pcstart && chromeStart)))
{
MyProcessName.Clear();
StartExE(palyExe, (app.HttpUrl.Replace("//", "|")).Split('/')[0].Replace("|", "//") + "|" + app.deviceid + "|" + app.configwebsocket + "|");
}
}
else
{
bool pcstart = false;
IntPtr Win = FindWindow(null, "WindowViewNew");//设置置顶
if (Win != null && Win != IntPtr.Zero)
{
pcstart = true;
SetWindowPos(Win, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
//CloseHandle(Win);
}
if (!pcstart)
{
MyProcessName.Clear();
app.AppPlayNameCH = "信息发布";
app.Appversion = app.Containerversion;
MyProcessName.Add("WindowView");
app.AppPlayName = "pcscreensavers";
app.CurAppPlayName = app.AppPlayName;
WindowViewNew windowView = new WindowViewNew(0);
windowView.Show();
}
}
#endregion
//if (app.AppList.Count > 0)
//{
// var needApp = app.AppTimeList.Where(i => i.BeginTimeSlot.Substring(0, 2) == DateTime.Now.ToString("HH")).Join(app.AppList, at => at.AppCode, al => al.Code, (at, al) => al).FirstOrDefault();
// if (needApp == null)
// {
// var defaultApp = app.AppList.Where(i => i.Default == bool.TrueString).FirstOrDefault();
// app.NowNeedPlayApp = defaultApp;
// }
// else
// {
// app.NowNeedPlayApp = needApp;
// }
//}
//string palyExe = string.Empty;
//if (app.NowNeedPlayApp == null)
//{
// app.AppPlayinfo = null;
// palyExe = app.configstartexe;
//}
//else
//{
// app.AppPlayinfo = app.NowNeedPlayApp;
// palyExe = app.NowNeedPlayApp.Startup;
//}
//if (!string.IsNullOrEmpty(palyExe))
//{
// bool pcstart = false;
// for (int i = 0; i < pro.Length; i++)
// {
// if (pro[i].ProcessName.ToLower() == app.AppPlayName.ToLower())
// {
// pcstart = true;
// break;
// }
// }
// if (!pcstart) {
// MyProcessName.Clear();
// StartExE(palyExe, (app.HttpUrl.Replace("//", "|")).Split('/')[0].Replace("|", "//") + "|" + app.deviceid + "|" + app.configwebsocket + "|");
// }
//}
//else {
// bool pcstart = false;
// IntPtr Win = FindWindow(null, "WindowViewNew");//设置置顶
// if (Win != null && Win != IntPtr.Zero)
// {
// pcstart = true;
// //SetWindowPos(Win, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
// }
// if (!pcstart)
// {
// MyProcessName.Clear();
// app.AppPlayNameCH = "信息发布";
// app.Appversion = app.Containerversion;
// MyProcessName.Add("WindowView");
// app.AppPlayName = "pcscreensavers";
// app.CurAppPlayName = app.AppPlayName;
// WindowViewNew windowView = new WindowViewNew(0);
// windowView.Show();
// }
//}
//if (app.AppPlayName == "pcscreensavers")
//{
//}
//if (app.AppPlayName == "")
//{
// timer.Stop();
// return;
//}
//MyProcessName.Clear();
//string playExe = string.Empty;
//if (app.NowNeedPlayApp == null)
//{
// app.AppPlayinfo = null;
// playExe = app.configstartexe;
//}
//else
//{
// app.AppPlayinfo = app.NowNeedPlayApp;
// playExe = app.NowNeedPlayApp.Startup;
//}
//if (!string.IsNullOrEmpty(playExe))
//{
// StartExE(playExe, (app.HttpUrl.Replace("//", "|")).Split('/')[0].Replace("|", "//") + "|" + app.deviceid + "|" + app.configwebsocket + "|");
//}
//else
//{
// app.AppPlayNameCH = "信息发布";
// app.Appversion = app.Containerversion;
// MyProcessName.Add("WindowView");
// app.AppPlayName = "pcscreensavers";
// app.CurAppPlayName = app.AppPlayName;
// WindowViewNew windowView = new WindowViewNew();
// windowView.Show();
//}
}
catch (Exception ex)
{
log.WriteLogFile(ex.ToString());
}
}
private void timerDownFiles_Tick(object sender, EventArgs e)
{
//try
//{
// if (DateTime.Now.Hour == 0) {
// PlayBackManage pbm = new PlayBackManage();
// Action ac3 = new Action(() =>
// {
// pbm.InitOutLineFiles();//下载定制节目组图片
// });
// ac3.BeginInvoke(null, null);
// }
//}
//catch (Exception ex)
//{
// log.WriteLogFile(ex.ToString());
//}
}
//bool isExecutionOpenApp = false;
///
/// 心跳线程:获取关机重启指令
///
private void HeatBeatGetShutDown()
{
string content = string.Empty;
string synetimeurl = AppDomain.CurrentDomain.BaseDirectory + "/exefile/synetime.bat";
if (HeatBeatThread == null)
{
//MqttClient mqttClient = new MqttClient();
if (!string.IsNullOrEmpty(app.configHttpUrl))
{
RabbitHostedService rabbitHostedService = new RabbitHostedService();
rabbitHostedService.Register();
//mqttClient.InitAsync();
RabbitHostedService.WebSocketReceiveEvent += new RabbitHostedService.WebSocketReceiveDelegate(WebSocketManage_WebSocketReceiveEvent);
MqServer.Create();
}
HeatBeatThread = new Thread(new ThreadStart(() =>
{
while (!isStop)
{
Thread.Sleep(30000);
//if (isExecutionOpenApp)
//{
// isExecutionOpenApp = false;
//}
try
{
//StartExE(synetimeurl, "");
app.IsCanConnect = MyHttpClient.IsCanConnect(app.HttpUrl);
if (string.IsNullOrEmpty(app.configHttpUrl))
{
content = httpmessage.HeatBeat();
}
else
{
content = httpmessage.HeatBeatForMqtt();
}
if (!string.IsNullOrEmpty(content))
{
Process MyProcess = new Process();
//设定程序名
MyProcess.StartInfo.FileName = "cmd.exe";
//关闭Shell的使用
MyProcess.StartInfo.UseShellExecute = false;
//重定向标准输入
MyProcess.StartInfo.RedirectStandardInput = true;
//重定向标准输出
MyProcess.StartInfo.RedirectStandardOutput = true;
//重定向错误输出
MyProcess.StartInfo.RedirectStandardError = true;
//设置不显示窗口
MyProcess.StartInfo.CreateNoWindow = true;
string cmdtext = string.Empty;
if (content.Equals("ShutDownTime"))
{
if (!string.IsNullOrEmpty(app.shutdowntime))
{
if (shutDownTime != app.shutdowntime)
{
shutDownTime = app.shutdowntime;
cmdtext = "schtasks /create /tn shutdownWindows /sc DAILY /st " + app.shutdowntime + " /tr \"shutdown -s -f -t 0\" -f"; //关机
log.WriteLogFile(cmdtext, "cmdexelog");
//执行VER命令
MyProcess.Start();
MyProcess.StandardInput.WriteLine(cmdtext);
}
}
else if (!string.IsNullOrEmpty(shutDownTime))
{
shutDownTime = string.Empty;
deleteSchtasks();
}
}
}
//if (app.NowAppName != "")
//{
// if (!app.appClick)
// {
// if (app.NowAppName != app.AppPlayinfo.Name)
// {
// //isExecutionOpenApp = true;
// //Thread.Sleep(10000);
// //打开应用
// IEnumerable exeinfo = app.AppList.Where(i => i.Name == app.NowAppName);
// if (exeinfo.Count() > 0)
// {
// //
// //log.WriteLogFile(exeinfo.Count().ToString());
// if (app.NowAppType != "bat" && app.NowAppType != "")
// {
// killExE();
// }
// //else if (app.NowAppType == "html")
// //{
// // app.winh5.WinClose();
// // //app.winh5 = null;
// //}
// string fileName = exeinfo.ElementAt(0).Startup;
// //if (string.IsNullOrEmpty(exeinfo.ElementAt(0).exestartname))
// //{
// // fileName = exeinfo.ElementAt(0).exepath;
// //}
// //else {
// // fileName = exeinfo.ElementAt(0).exepath + "/" + exeinfo.ElementAt(0).exestartname;
// //}
// if (ChangeExE(fileName, exeinfo.ElementAt(0)))
// {
// app.AppPlayinfo = exeinfo.ElementAt(0);
// app.AppPlayNameCH = "";
// app.Appversion = "";
// }
// else
// {
// app.AppPlayName = "";
// app.AppPlayNameCH = "";
// app.Appversion = "";
// //打开失败
// }
// //Thread.Sleep(20000);
// }
// }
// }
//}
}
catch (Exception ex)
{
log.WriteLogFile(ex.ToString());
}
finally
{
Thread.Sleep(10000);
SetProcessWorkingSetSize(Process.GetCurrentProcess().Handle, -1, -1);
}
}
}));
}
HeatBeatThread.IsBackground = true;
HeatBeatThread.Start();
}
///
/// 打开外部exe应用程序
/// 应用程序地址
///
///
private bool ChangeExE(string path, string param = "")
{
try
{
if (!File.Exists(path) && !path.StartsWith("http:"))
{
//System.Windows.MessageBox.Show("应用程序打开失败:。。。" + path + " 文件不存在");
log.WriteLogFile("应用程序打开失败:" + path + " 文件不存在", "UCAppButtonlog");
return false;
}
if (path.Substring(path.Length - 4, 4).ToLower().Equals(".bat"))
{
param = "";
Process myprocess = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo(path, param);
path = path.Replace("\\", "/");
startInfo.Verb = "runas";
startInfo.CreateNoWindow = true;
startInfo.WorkingDirectory = path.Substring(0, path.LastIndexOf("/"));//设置应用程序在其所在目录
myprocess.StartInfo = startInfo;
myprocess.StartInfo.UseShellExecute = false;
myprocess.StartInfo.CreateNoWindow = true;
myprocess.Start();
//MyProcessName.Add("chrome");
app.AppPlayName = "chrome";
app.CurAppPlayName = app.AppPlayName;
app.NowAppType = "bat";
//startexe = true;
//timer.Start();
log.WriteLogFile("打开成功", "startlog");
}
else
{
Process myprocess = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo(path, param);
path = path.Replace("\\", "/");
startInfo.WorkingDirectory = path.Substring(0, path.LastIndexOf("/"));//设置应用程序在其所在目录
startInfo.Verb = "runas";
startInfo.CreateNoWindow = true;
myprocess.StartInfo = startInfo;
myprocess.StartInfo.UseShellExecute = false;
myprocess.Start();
//MyProcessName.Add(myprocess.ProcessName);
app.NowAppType = "exe";
app.AppPlayName = myprocess.ProcessName;
app.CurAppPlayName = app.AppPlayName;
//startexe = true;
}
//Process myprocess = new Process();
//ProcessStartInfo startInfo = new ProcessStartInfo(path, param);
//path = path.Replace("\\", "/");
//startInfo.WorkingDirectory = path.Substring(0, path.LastIndexOf("/"));//设置应用程序在其所在目录工作
//myprocess.StartInfo = startInfo;
//myprocess.StartInfo.UseShellExecute = false;
//myprocess.Start();
//ProcessName = myprocess.ProcessName;
return true;
}
catch (Exception ex)
{
log.WriteLogFile(ex.ToString(), "UCAppButtonlog");
return false;
}
}
///
/// 窗体加载事件
///
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
try
{
deleteSchtasks("ContainerService");
string exePath = AppDomain.CurrentDomain.BaseDirectory + "/ContainerService.exe";
string cmdtext = "schtasks /create /tn ContainerService /sc minute /mo 2 /tr \"" + exePath + "\" -f"; //关机
createSchtasks(cmdtext);
//loads();
//this.ShowInTaskbar = false;//使程序不在任务栏显示
//app.HttpUrl = "";
Class_Config config = new Class_Config();
//config.ReadAppInfo(ref app.NowAppList);
config.LoadInitialConfig();
config.LoadConfig();//加载注册文件(楼栋楼层等设备信息)
app.Containerversion = config.GetVersion();
log.WriteLogFile(app.HttpUrl, "config");
log.WriteLogFile(app.configurl, "config");
if (app.BuildingID.Equals("") || app.Floor.Equals(""))
{
//app.HttpUrl = ConfigurationManager.AppSettings["RemoteAddress"]; //服务器地址
// app.HttpUrl = app.configurl;
//配置文件不存在则重新注册
this.WindowState = WindowState.Minimized;
if (string.IsNullOrEmpty(app.configHttpUrl))
{
app.HttpUrl = app.configurl;
GetUrlForLocal MyService = new GetUrlForLocal();
MyService.ShowDialog();
if (MyService.DialogResult == false)
{
OnMenuItemExitClick(null, null);
return;
}
}
else
{
GetUrl MyService = new GetUrl();
MyService.ShowDialog();
if (MyService.DialogResult == false)
{
OnMenuItemExitClick(null, null);
return;
}
}
}
else if (!app.HttpUrl.Replace("\\", "/").Equals(app.configurl.Replace("\\", "/")))
{
app.HttpUrl = app.configurl;
GetUrlForLocal MyService = new GetUrlForLocal();
MyService.ShowDialog();
if (MyService.DialogResult == false)
{
OnMenuItemExitClick(null, null);
return;
}
}
else
{
app.IsCanConnect = MyHttpClient.IsCanConnect(app.HttpUrl);
string msg = "";
log.WriteLogFile(app.IsCanConnect.ToString(), "connect");
bool flag = httpmessage.UploadDeviceInfo(app.BuildingID, app.Floor, app.DeviceType, ref msg, false);
//Action ac = new Action(() =>
//{
log.WriteLogFile(flag + "---", "config");
deleteSchtasks();
if (app.IsCanConnect && !flag)
{
app.deviceid = "";
if (string.IsNullOrEmpty(app.configHttpUrl))
{
GetUrlForLocal MyService = new GetUrlForLocal();
MyService.ShowDialog();
if (MyService.DialogResult == false)
{
OnMenuItemExitClick(null, null);
return;
}
}
else
{
GetUrl MyService = new GetUrl();
MyService.ShowDialog();
if (MyService.DialogResult == false)
{
OnMenuItemExitClick(null, null);
return;
}
}
return;
}
else
{
if (!string.IsNullOrEmpty(app.shutdowntime))
{
createSchtasks();
}
}
//});
//ac.BeginInvoke(null, null);
}
//btn_OK.Visibility = System.Windows.Visibility.Hidden;
if (!app.deviceid.Equals(""))
{
Terminalid.Text = "当前终端编号:" + app.deviceid;
txtVersion.Text = app.Containerversion;
if (!string.IsNullOrEmpty(app.devicemark))
Terminalmark.Text = "当前终端标识:" + app.devicemark;
// this.WindowState = WindowState.Normal;
httpmessage.LoadBG();
IntPtr Win = FindWindow(null, "BGPage"); //Win_h5Page是我的程序中需要置顶的窗体的名字
if (Win != null)
{
SetWindowPos(Win, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
}
string errorMsg = "";
config.ReadAppInfo(ref app.AppList);
config.ReadAppTimeInfo(ref app.AppTimeList);
httpmessage.LoadAppConfig(ref errorMsg);
httpmessage.LoadScreenTime();
//if (ConfigurationManager.AppSettings["isOnlyScreensaver"].Equals("1"))
//{
// httpmessage.LoadAppConfig(ref errorMsg);
//}
IntPtr WinMain = FindWindow(null, "MainWindow"); //Win_h5Page是我的程序中需要置顶的窗体的名字
if (WinMain != null)
{
SetWindowPos(WinMain, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
}
IntPtr WinBG = FindWindow(null, "BGPage"); //Win_h5Page是我的程序中需要置顶的窗体的名字
if (WinBG != null)
{
SetWindowPos(WinBG, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
}
Action UploadApp = new Action(() =>
{
HeatBeatGetShutDown();
if (string.IsNullOrEmpty(app.configHttpUrl))
{
WebSocketManage.WebSocketReceiveEvent += new WebSocketManage.WebSocketReceiveDelegate(WebSocketManage_WebSocketReceiveEvent);
web.OpenWebSocket();
}
WebSocketManageForLive webForLive = new WebSocketManageForLive();
webForLive.OpenWebSocket();
//string msg = "";
//httpmessage.UploadAppInfo(ref msg);
});
UploadApp.BeginInvoke(null, null);
//app.winh6 = new H5Page("");
//app.winh6.Show();
if (app.AppList.Count > 0)
{
var needApp = app.AppTimeList.Where(i => i.BeginTimeSlot.Substring(0, 2) == DateTime.Now.ToString("HH")).Join(app.AppList, at => at.AppCode, al => al.Code, (at, al) => al).FirstOrDefault();
if (needApp == null)
{
var defaultApp = app.AppList.Where(i => i.Default == bool.TrueString).FirstOrDefault();
app.NowNeedPlayApp = defaultApp;
}
else
{
app.NowNeedPlayApp = needApp;
}
}
string palyExe = string.Empty;
if (app.NowNeedPlayApp == null)
{
app.AppPlayinfo = null;
palyExe = app.configstartexe;
}
else
{
app.AppPlayinfo = app.NowNeedPlayApp;
palyExe = app.NowNeedPlayApp.Startup;
}
string synetimeurl = AppDomain.CurrentDomain.BaseDirectory + "/exefile/synetime.bat";
StartExE(synetimeurl, "");
string windowsset = AppDomain.CurrentDomain.BaseDirectory + "/exefile/windows.bat";
StartExE(windowsset, "");
if (!string.IsNullOrEmpty(palyExe))
{
mouse_event(MouseEventFlag.LeftDown | MouseEventFlag.LeftUp, 0, 0, 0, UIntPtr.Zero);
Action ac1 = new Action(() =>
{
StartExE(palyExe, (app.HttpUrl.Replace("//", "|")).Split('/')[0].Replace("|", "//") + "|" + app.deviceid + "|" + app.configwebsocket + "|1");
});
ac1.BeginInvoke((o) =>
{
this.Dispatcher.Invoke(new Action(() =>
{
pbm.DownResource();
//if (mIdleTimer != null)
//{
// mIdleTimer.Start();
//}
this.WindowState = WindowState.Minimized;
//if (startexe)
//{
// app.AppPlayinfo.AppID = "1";
// this.WindowState = System.Windows.WindowState.Minimized;
//}
//else
//{
// this.WindowState = WindowState.Minimized;
//}
}));
}, null);
}
else
{
app.AppPlayNameCH = "信息发布";
app.AppPlayName = "pcscreensavers";
app.Appversion = app.Containerversion;
app.CurAppPlayName = app.AppPlayName;
MyProcessName.Add("WindowView");
//if (mIdleTimer != null)
//{
// mIdleTimer.Start();
//}
WindowViewNew windowView = new WindowViewNew(0);
windowView.Show();
}
if (app.AppList.Count > 1)
{
this.WindowState = WindowState.Minimized;
if (app.AppList != null && app.AppList.Count > 1)
{
WindowButton win = new WindowButton();
win.Show();
}
}
backgroundWorker.RunWorkerAsync();
log.DeleteFiles();
//PlayBackManage pbm = new PlayBackManage();
// Action ac3 = new Action(() =>
// {
// pbm.InitOutLineFiles();//下载定制节目组图片
// });
// ac3.BeginInvoke(null, null);
// timerDownFiles.Start();
this.WindowState = WindowState.Minimized;
}
else
{
Terminalid.Text = "未获得终端号请重新注册。";
return;
}
}
catch (Exception ex)
{
log.WriteLogFile(ex.ToString());
}
}
///
/// websocket委托事件
///
private void WebSocketManage_WebSocketReceiveEvent(string type, string message)
{
if (type == "apppublish")//开始下载
{
//ChatWebSocketMiddleware.allSockets.ToList().ForEach(s => s.Send(JsonConvert.SerializeObject(app.AppList)));
//downLineExE();
//if (ConfigurationManager.AppSettings["MenuShow"].Equals("0")) //判断是否有悬浮框
//{
if (app.AppList.Count > 1)
{
IntPtr Win = FindWindow(null, "WindowButton"); //置顶窗体
//if (Win != null)
//{
// SendMessage(Win, WM_CLOSE, 0, 0);
//}
if (Win == null || Win == IntPtr.Zero)
{
this.Dispatcher.Invoke(new Action(() =>
{
WindowButton WinButton = new WindowButton();
//adView.SetADImage(fileName, app.insertAD.Duration);
WinButton.Show();
log.WriteLogFile("打开悬浮框");
IntPtr Win1 = FindWindow(null, "WindowButton");//设置置顶
SetWindowPos(Win1, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
IntPtr Win2 = FindWindow(null, "WindowViewNew");//设置置顶
if (Win2 != null && Win2 != IntPtr.Zero)
{
SetWindowPos(Win2, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
}
}));
}
//}
}
}
else
if (type == "appupdate")//开始下载
{
//downLineExE();
}
else if (type == "appdown")
{
if (app.AppList.Count <= 1)
{
IntPtr Win = FindWindow(null, "WindowButton"); //置顶窗体
if (Win != null && Win != IntPtr.Zero)
{
SendMessage(Win, WM_CLOSE, 0, 0);
}
}
//ChatWebSocketMiddleware.allSockets.ToList().ForEach(s => s.Send(JsonConvert.SerializeObject(app.AppList)));
//appDown();
}
else if (type == "apptimeset")
{
//var curApp = app.NowAppList.Where(i => i.AppID == app.DefaultAppCode).FirstOrDefault();
//if (curApp != null)
//{
// app.configstartexe = string.IsNullOrEmpty(curApp.exestartname) ? curApp.exepath : (curApp.exepath + "/" + curApp.exestartname);
//}
//else
//{
// app.configstartexe = "";
//}
}
else if (type == "appclock")//打开
{
//if (string.IsNullOrEmpty(app.AppStartinfo.exestartname))
//{
// killExE();
// startexe = false;
// if (!string.IsNullOrEmpty(app.configstartexe))
// StartExE(app.configstartexe, (app.HttpUrl.Replace("//", "|")).Split('/')[0].Replace("|", "//") + "|" + app.deviceid + "|" + app.configwebsocket + "|1");
// if (startexe)
// app.AppPlayinfo.AppID = "1";
//}
//else if (!app.AppStartinfo.AppID.Equals(app.AppStartinfo.AppID))
//{
// string path = AppDomain.CurrentDomain.BaseDirectory + "/exefile/" + app.AppPlayDir;
// DirectoryInfo dir = new DirectoryInfo(path);
// if (dir == null)
// {
// //System.Windows.MessageBox.Show(app.AppStartinfo.exestartname + "应用程序文件不存在");
// return;
// }
// string exepath = "";
// ListFiles(dir, app.AppStartinfo.exestartname, ref exepath);
// if (exepath != "")
// {
// killExE();
// startexe = false;
// StartExE(exepath);
// if (startexe)
// app.AppPlayinfo = app.AppStartinfo;
// }
// else
// {
// //System.Windows.MessageBox.Show(app.AppStartinfo.exestartname + "文件不存在");
// }
//}
}
else if (type.Equals("screenshot") || type.Equals("cloud-screenshot"))
{
string Mess = "";
if (!string.IsNullOrEmpty(app.deviceid))
{
string[] IP = app.LocalIP.Split('.');
string imgname = app.deviceid.Replace("-", "") + System.DateTime.Now.ToString("yyMMddhhmmssffff") + ".jpg";
string imgPath = Class_Config.PrintScreen(imgname);
httpmessage.UpLoadImg(ref Mess, imgPath, imgname, app.screenshotUserName, type.Equals("screenshot") ? "local" : "cloud");
}
}
else if (type.Equals("restart"))
{
Process MyProcess = new Process();
//设定程序名
MyProcess.StartInfo.FileName = "cmd.exe";
//关闭Shell的使用
MyProcess.StartInfo.UseShellExecute = false;
//重定向标准输入
MyProcess.StartInfo.RedirectStandardInput = true;
//重定向标准输出
MyProcess.StartInfo.RedirectStandardOutput = true;
//重定向错误输出
MyProcess.StartInfo.RedirectStandardError = true;
//设置不显示窗口
MyProcess.StartInfo.CreateNoWindow = true;
string cmdtext = string.Empty;
cmdtext = @"Shutdown -f -r -t 0"; //重启
log.WriteLogFile(cmdtext, "cmdexelog");
//执行VER命令
MyProcess.Start();
MyProcess.StandardInput.WriteLine(cmdtext);
log.WriteLogFile("重启", "cmdexelog");
string output = "";
char[] outl = new char[2048];
string error = "";
using (System.IO.StreamReader myOutput = MyProcess.StandardOutput)
{
myOutput.Read(outl, 0, 2048);
output = new string(outl);
log.WriteLogFile(output, "cmdexelog");
}
using (System.IO.StreamReader myError = MyProcess.StandardError)
{
myError.Read(outl, 0, 1024);
error = new string(outl);
log.WriteLogFile(error, "cmdexelog");
}
}
else if (type.Equals("shutdown"))
{
Process MyProcess = new Process();
//设定程序名
MyProcess.StartInfo.FileName = "cmd.exe";
//关闭Shell的使用
MyProcess.StartInfo.UseShellExecute = false;
//重定向标准输入
MyProcess.StartInfo.RedirectStandardInput = true;
//重定向标准输出
MyProcess.StartInfo.RedirectStandardOutput = true;
//重定向错误输出
MyProcess.StartInfo.RedirectStandardError = true;
//设置不显示窗口
MyProcess.StartInfo.CreateNoWindow = true;
string cmdtext = string.Empty;
cmdtext = @"Shutdown -f -s -t 0"; //关机
log.WriteLogFile(cmdtext, "cmdexelog");
//执行VER命令
MyProcess.Start();
MyProcess.StandardInput.WriteLine(cmdtext);
log.WriteLogFile("关机", "cmdexelog");
string output = "";
char[] outl = new char[2048];
string error = "";
using (System.IO.StreamReader myOutput = MyProcess.StandardOutput)
{
myOutput.Read(outl, 0, 2048);
output = new string(outl);
log.WriteLogFile(output, "cmdexelog");
}
using (System.IO.StreamReader myError = MyProcess.StandardError)
{
myError.Read(outl, 0, 1024);
error = new string(outl);
log.WriteLogFile(error, "cmdexelog");
}
}
else if (type.Equals("turnoff") || type.Equals("turnofftouch"))
{
bool is64Bit;
is64Bit = Environment.Is64BitOperatingSystem;
int i = 0;
IntPtr p = new IntPtr(i);
string tpath = System.Environment.CurrentDirectory;
string OKorNO = "disable";
string systemWordLength;
//检测系统是64位还是32位
if (is64Bit == true)
{
systemWordLength = "x64";
}
else
{
systemWordLength = "x86";
}
ShellExecute(p, "runas", tpath + "\\devcon\\" + systemWordLength + "\\devcon.exe", OKorNO + " *HID* /c net user administrator /active:yes", "", (int)ShowWindowCommands.SW_HIDE);
ShellExecute(p, "runas", tpath + "\\devcon\\" + systemWordLength + "\\devcon.exe", "enable HID_DEVICE_SYSTEM_MOUSE user administrator /active:yes", "", (int)ShowWindowCommands.SW_HIDE);
httpmessage.ScreenOperSuccess(0);
}
else if (type.Equals("turnon") || type.Equals("turnontouch"))
{
bool is64Bit;
is64Bit = Environment.Is64BitOperatingSystem;
int i = 0;
IntPtr p = new IntPtr(i);
string tpath = System.Environment.CurrentDirectory;
string OKorNO = "enable";
string systemWordLength;
//检测系统是64位还是32位
if (is64Bit == true)
{
systemWordLength = "x64";
}
else
{
systemWordLength = "x86";
}
ShellExecute(p, "runas", tpath + "\\devcon\\" + systemWordLength + "\\devcon.exe", OKorNO + " *HID* /c net user administrator /active:yes", "", (int)ShowWindowCommands.SW_HIDE);
httpmessage.ScreenOperSuccess(1);
}
else if (type.Equals("devnumedit"))
{
DevNumEdit();
}
else if (type.Equals("bgset"))
{
BGSet();
}
else if (type.Equals("startexplorer"))
{
StartExplorer();
}
else if (type.Equals("killexplorer"))
{
KillExplorer();
}
else if (type.Equals("shutdowntime"))
{
deleteSchtasks();
if (!string.IsNullOrEmpty(app.shutdowntime))
{
createSchtasks();
}
}
}
private void deleteSchtasks(string schtaskName)
{
try
{
Process MyProcess = new Process();
//设定程序名
MyProcess.StartInfo.FileName = "cmd.exe";
//关闭Shell的使用
MyProcess.StartInfo.UseShellExecute = false;
//重定向标准输入
MyProcess.StartInfo.RedirectStandardInput = true;
//重定向标准输出
MyProcess.StartInfo.RedirectStandardOutput = true;
//重定向错误输出
MyProcess.StartInfo.RedirectStandardError = true;
//设置不显示窗口
MyProcess.StartInfo.CreateNoWindow = true;
string cmdtext = "schtasks /delete /tn " + schtaskName + " -f"; //关机
log.WriteLogFile(cmdtext, "cmdexelog");
//执行VER命令
MyProcess.Start();
MyProcess.StandardInput.WriteLine(cmdtext);
}
catch (Exception ex)
{
log.WriteLogFile(ex.ToString());
}
}
private void createSchtasks(string cmdtext)
{
try
{
Process MyProcess = new Process();
//设定程序名
MyProcess.StartInfo.FileName = "cmd.exe";
//关闭Shell的使用
MyProcess.StartInfo.UseShellExecute = false;
//重定向标准输入
MyProcess.StartInfo.RedirectStandardInput = true;
//重定向标准输出
MyProcess.StartInfo.RedirectStandardOutput = true;
//重定向错误输出
MyProcess.StartInfo.RedirectStandardError = true;
//设置不显示窗口
MyProcess.StartInfo.CreateNoWindow = true;
log.WriteLogFile(cmdtext, "cmdexelog");
//执行VER命令
MyProcess.Start();
MyProcess.StandardInput.WriteLine(cmdtext);
}
catch (Exception ex)
{
log.WriteLogFile(ex.ToString());
}
}
///
/// 窗体关闭事件
///
///
private void WebSocketManageForLive_WebSocketReceiveEvent(string type, string message)
{
log.WriteLogFile(type, "live");
if (type == "live")//开始下载
{
//app.AppPlayNameCH = "直播";
//app.CurAppPlayName = "live";
//MyProcessName.Add("LiveShow");
try
{
if (app.live.OldLiveCode != app.live.LiveCode)
{
try
{
app.isLoadLive = false;
//结束进程
IntPtr WinLiveShow = FindWindow(null, "LiveShow"); //置顶窗体
if (WinLiveShow != null && WinLiveShow != IntPtr.Zero)
{
SendMessage(WinLiveShow, WM_CLOSE, 0, 0);
}
app.live.OldLiveCode = app.live.LiveCode;
Action UploadApp = new Action(() =>
{
app.isLoadLive = true;
App.Current.Dispatcher.Invoke((Action)(() =>
{
try
{
LiveShow liveShow = new LiveShow();
liveShow.Show();
}
catch (Exception ex)
{
log.WriteLogFile(ex.ToString(), "errorrrr");
}
}));
});
UploadApp.BeginInvoke(null, null);
IntPtr Win = FindWindow(null, "WindowViewNew"); //置顶窗体
if ((Win != null && Win != IntPtr.Zero))
{
SendMessage(Win, WM_CLOSE, 0, 0);
}
}
catch (Exception e)
{
log.WriteLogFile(e.ToString(), "liveerror");
Thread.Sleep(1000);
app.isLoadLive = false;
//结束进程
IntPtr WinLiveShow = FindWindow(null, "LiveShow"); //置顶窗体
if (WinLiveShow != null && WinLiveShow != IntPtr.Zero)
{
SendMessage(WinLiveShow, WM_CLOSE, 0, 0);
}
app.live.OldLiveCode = app.live.LiveCode;
Action UploadApp = new Action(() =>
{
app.isLoadLive = true;
App.Current.Dispatcher.Invoke((Action)(() =>
{
try
{
LiveShow liveShow = new LiveShow();
liveShow.Show();
}
catch (Exception ex)
{
log.WriteLogFile(ex.ToString(), "errorrrr");
}
}));
});
UploadApp.BeginInvoke(null, null);
IntPtr Win = FindWindow(null, "WindowViewNew"); //置顶窗体
if ((Win != null && Win != IntPtr.Zero))
{
SendMessage(Win, WM_CLOSE, 0, 0);
}
}
}
else
{
bool isStartVlc = false;
//结束进程
IntPtr WinLiveShow = FindWindow(null, "LiveShow"); //置顶窗体
if (WinLiveShow != null && WinLiveShow != IntPtr.Zero)
{
isStartVlc = true;
}
if (!isStartVlc && !app.isLoadLive)
{
try
{
app.live.OldLiveCode = app.live.LiveCode;
app.isLoadLive = true;
App.Current.Dispatcher.Invoke((Action)(() =>
{
try
{
LiveShow liveShow = new LiveShow();
liveShow.Show();
}
catch (Exception ex)
{
log.WriteLogFile(ex.ToString(), "errorrrr");
}
}));
IntPtr Win = FindWindow(null, "WindowViewNew"); //置顶窗体
if ((Win != null && Win != IntPtr.Zero))
{
SendMessage(Win, WM_CLOSE, 0, 0);
}
}
catch (Exception e)
{
log.WriteLogFile(e.ToString(), "liveerror");
Thread.Sleep(1000);
if (!app.isLoadLive)
{
app.isLoadLive = true;
app.live.OldLiveCode = app.live.LiveCode;
App.Current.Dispatcher.Invoke((Action)(() =>
{
try
{
LiveShow liveShow = new LiveShow();
liveShow.Show();
}
catch (Exception ex)
{
log.WriteLogFile(ex.ToString(), "errorrrr");
}
}));
IntPtr Win = FindWindow(null, "WindowViewNew"); //置顶窗体
if ((Win != null && Win != IntPtr.Zero))
{
SendMessage(Win, WM_CLOSE, 0, 0);
}
}
}
}
else
{
if (app.live.HFilePath != app.curLive.hFilePath)
{
app.curLive.hFilePath = app.live.HFilePath;
var model = new { Type = "ADImage", Parameter = app.live.HFilePath };
byte[] data = Encoding.Default.GetBytes(JsonConvert.SerializeObject(model));
//6、发送消息
socket.Send(data, 0, data.Length, SocketFlags.None); //指定套接字的发送行为
}
if (socket.Connected)//判断客户端是否还在连接
{
app.curLive.vFilePath = app.live.VFilePath;
var model = new { Type = "Image", Parameter = string.Join(";", app.live.VFilePath) };
byte[] data = Encoding.Default.GetBytes(JsonConvert.SerializeObject(model));
//6、发送消息
socket.Send(data, 0, data.Length, SocketFlags.None); //指定套接字的发送行为
}
//bool isReload = false;
//if (SystemParameters.PrimaryScreenWidth > SystemParameters.PrimaryScreenHeight)
//{
// if (!string.IsNullOrEmpty(app.live.HFilePath))
// {
// isReload = true;
// }
// else
// {
// //app.LiveReload = true;
// }
//}
//else
//{
// if (!string.IsNullOrEmpty(app.live.VFilePath))
// {
// isReload = true;
// }
// else
// {
// }
//}
}
}
}
catch (Exception e)
{
log.WriteLogFile(e.ToString(), "liveerror");
}
}
else if (type == "shutdownlive")
{
try
{
//IntPtr Win = FindWindow(null, "WindowView"); //置顶窗体
//if ((Win == null || Win == IntPtr.Zero))
//{
//}
app.isLoadLive = false;
//结束进程
IntPtr WinLive = FindWindow(null, "LiveShow"); //置顶窗体
if (WinLive != null && WinLive != IntPtr.Zero)
{
Action UploadApp = new Action(() =>
{
App.Current.Dispatcher.Invoke((Action)(() =>
{
try
{
app.AppPlayNameCH = "信息发布";
app.CurAppPlayName = "pcscreensavers";
app.Appversion = app.Containerversion;
MyProcessName.Add("WindowView");
WindowViewNew windowView = new WindowViewNew(0);
windowView.Show();
}
catch (Exception ex)
{
log.WriteLogFile(ex.ToString(), "errorrrr");
}
}));
});
UploadApp.BeginInvoke(null, null);
SendMessage(WinLive, WM_CLOSE, 0, 0);
}
//结束进程
//IntPtr WinLivePage = FindWindow(null, "LivePage"); //置顶窗体
//if (WinLivePage != null && WinLivePage != IntPtr.Zero)
//{
// SendMessage(WinLivePage, WM_CLOSE, 0, 0);
//}
IntPtr WindowView = FindWindow(null, "WindowViewNew"); //置顶窗体
if ((WindowView != null && WindowView != IntPtr.Zero))
{
SetWindowPos(WindowView, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
}
}
catch (Exception ex)
{
log.WriteLogFile(ex.ToString(), "shutdownliveerror");
}
}
else if (type == "livecoupon" || type == "getcoupon" || type == "shutdowncoupon")
{
if (socket.Connected)//判断客户端是否还在连接
{
var model = new { Type = type };
byte[] data = Encoding.Default.GetBytes(JsonConvert.SerializeObject(model));
//6、发送消息
socket.Send(data, 0, data.Length, SocketFlags.None); //指定套接字的发送行为
}
}
else if (type == "like" || type == "watchnum")
{
if (socket.Connected)//判断客户端是否还在连接
{
var model = new { Type = type, Parameter = new { likes = app.live.Likes, watchNum = app.live.WatchNum } };
byte[] data = Encoding.Default.GetBytes(JsonConvert.SerializeObject(model));
//6、发送消息
socket.Send(data, 0, data.Length, SocketFlags.None); //指定套接字的发送行为
}
//if (app.curLive != null)
//{
// app.curLive.likes = app.live.Likes;
// app.curLive.watchNum = app.live.WatchNum;
//}
//log.WriteLogFile(ChatWebSocketServicesFoH5.allSockets.Count.ToString() + "like个数", "111");
//ChatWebSocketServicesFoH5.allSockets.ToList().ForEach(s => s.Send("like"));
}
else if (type == "playprog")
{
//结束进程
IntPtr WinLive = FindWindow(null, "LiveShow"); //置顶窗体
if (WinLive != null && WinLive != IntPtr.Zero)
{
app.isLoadLive = false;
SendMessage(WinLive, WM_CLOSE, 0, 0);
}
//结束进程
//IntPtr WinLivePage = FindWindow(null, "LivePage"); //置顶窗体
//if (WinLivePage != null && WinLivePage != IntPtr.Zero)
//{
// SendMessage(WinLivePage, WM_CLOSE, 0, 0);
//}
IntPtr brandWin = FindWindow(null, "BrandProg"); //置顶窗体
if ((brandWin == null || brandWin == IntPtr.Zero))
{
Action UploadApp = new Action(() =>
{
App.Current.Dispatcher.Invoke((Action)(() =>
{
try
{
BrandProg prog = new BrandProg();
prog.Show();
}
catch (Exception ex)
{
log.WriteLogFile(ex.ToString(), "errorrrr");
}
}));
});
UploadApp.BeginInvoke(null, null);
}
IntPtr Win = FindWindow(null, "WindowViewNew"); //置顶窗体
if ((Win != null && Win != IntPtr.Zero))
{
SendMessage(Win, WM_CLOSE, 0, 0);
}
//if (socket.Connected)//判断客户端是否还在连接
//{
// var model = new { Type = type };
// byte[] data = Encoding.Default.GetBytes(JsonConvert.SerializeObject(model));
// //6、发送消息
// socket.Send(data, 0, data.Length, SocketFlags.None); //指定套接字的发送行为
//}
}
else if (type == "shutdownprog")
{
}
}
private void MainWindow_Closed(object sender, EventArgs e)
{
try
{
isStop = true;
StartExplorer();
deleteSchtasks();
killExE();
Process[] process = Process.GetProcesses();
foreach (Process prc in process)
{
if (prc.ProcessName.Equals(System.Diagnostics.Process.GetCurrentProcess().ProcessName))
prc.Kill();
}
}
catch (Exception)
{
Process[] process = Process.GetProcesses();
foreach (Process prc in process)
{
if (prc.ProcessName == "Container")
prc.CloseMainWindow();
}
}
}
///
/// 打开客户定制节目组应用程序
/// 应用程序地址
///
private void StartCScreen()
{
try
{
string path = Environment.CurrentDirectory + "/CScreen/ScreenSavers.exe";
if (!File.Exists(path))
{
return;
}
Process myprocess = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo(path);
startInfo.Verb = "runas";
startInfo.CreateNoWindow = true;
path = path.Replace("\\", "/");
startInfo.WorkingDirectory = path.Substring(0, path.LastIndexOf("/"));//设置应用程序在其所在目录
myprocess.StartInfo = startInfo;
myprocess.StartInfo.UseShellExecute = false;
myprocess.Start();
}
catch (Exception ex)
{
log.WriteLogFile(ex.ToString());
//this.Openexe.Visible = true;
startexe = false;
//System.Windows.MessageBox.Show("应用程序打开失败:" + ex.ToString());
}
}
///
/// 打开外部exe应用程序
/// 应用程序地址
///
private void StartExE(string path, string param = "")
{
try
{
timer.Stop();
if (!File.Exists(path) && !path.StartsWith("http:"))
{
if (!File.Exists(System.Windows.Forms.Application.ExecutablePath.Replace("\\", "/").Substring(0, System.Windows.Forms.Application.ExecutablePath.Replace("\\", "/").LastIndexOf("/")) + path))
{
OnReLoginClick(null, null);
startexe = false;
return;
}
else
{
path = System.Windows.Forms.Application.ExecutablePath.Replace("\\", "/").Substring(0, System.Windows.Forms.Application.ExecutablePath.Replace("\\", "/").LastIndexOf("/")) + path;
}
}
log.WriteLogFile(path.Substring(path.Length - 4, 4).ToLower(), "startlog");
if (path.Substring(path.Length - 4, 4).ToLower().Equals(".bat"))
{
param = "";
Process myprocess = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo(path, param);
startInfo.Verb = "runas";
startInfo.CreateNoWindow = true;
path = path.Replace("\\", "/");
startInfo.WorkingDirectory = path.Substring(0, path.LastIndexOf("/"));//设置应用程序在其所在目录
myprocess.StartInfo = startInfo;
myprocess.StartInfo.UseShellExecute = false;
myprocess.StartInfo.CreateNoWindow = true;
myprocess.Start();
MyProcessName.Add("chrome");
app.AppPlayName = "chrome";
app.CurAppPlayName = app.AppPlayName;
app.NowAppType = "bat";
startexe = true;
timer.Start();
log.WriteLogFile("打开成功", "startlog");
}
else
{
Process myprocess = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo(path, param);
path = path.Replace("\\", "/");
startInfo.WorkingDirectory = path.Substring(0, path.LastIndexOf("/"));//设置应用程序在其所在目录
startInfo.Verb = "runas";
startInfo.CreateNoWindow = true;
myprocess.StartInfo = startInfo;
myprocess.StartInfo.UseShellExecute = false;
myprocess.StartInfo.CreateNoWindow = true;
myprocess.Start();
MyProcessName.Add(myprocess.ProcessName);
app.AppPlayName = myprocess.ProcessName;
app.CurAppPlayName = myprocess.ProcessName;
app.NowAppType = "exe";
startexe = true;
timer.Start();
}
}
catch (Exception ex)
{
log.WriteLogFile(ex.ToString());
startexe = false;
}
}
///
/// 关闭已打开外部应用程序
///
private void killExE()
{
try
{
if (app.NowAppType == "exe")
{
Process[] pro = Process.GetProcesses();
for (int i = 0; i < pro.Length; i++)
{
//log.WriteLogFile(pro[i].ProcessName.ToLower());
if (pro[i].ProcessName.ToLower() == app.AppPlayName.ToLower())
{
pro[i].Kill();//结束进程
app.AppPlayName = "";
app.CurAppPlayName = app.AppPlayName;
app.NowAppType = "";
if (MyProcessName.Count > 0)
MyProcessName.RemoveAt(0);//移除进程列表中的元素
return;
}
}
}
}
catch (Exception ex)
{
log.WriteLogFile(ex.ToString());
}
}
///
/// 删除每日定时关机任务
///
private void deleteSchtasks()
{
try
{
Process MyProcess = new Process();
//设定程序名
MyProcess.StartInfo.FileName = "cmd.exe";
//关闭Shell的使用
MyProcess.StartInfo.UseShellExecute = false;
//重定向标准输入
MyProcess.StartInfo.RedirectStandardInput = true;
//重定向标准输出
MyProcess.StartInfo.RedirectStandardOutput = true;
//重定向错误输出
MyProcess.StartInfo.RedirectStandardError = true;
//设置不显示窗口
MyProcess.StartInfo.CreateNoWindow = true;
string cmdtext = "schtasks /delete /tn shutdownWindows -f"; //关机
log.WriteLogFile(cmdtext, "cmdexelog");
//执行VER命令
MyProcess.Start();
MyProcess.StandardInput.WriteLine(cmdtext);
}
catch (Exception ex)
{
log.WriteLogFile(ex.ToString());
}
}
private void createSchtasks()
{
try
{
Process MyProcess = new Process();
//设定程序名
MyProcess.StartInfo.FileName = "cmd.exe";
//关闭Shell的使用
MyProcess.StartInfo.UseShellExecute = false;
//重定向标准输入
MyProcess.StartInfo.RedirectStandardInput = true;
//重定向标准输出
MyProcess.StartInfo.RedirectStandardOutput = true;
//重定向错误输出
MyProcess.StartInfo.RedirectStandardError = true;
//设置不显示窗口
MyProcess.StartInfo.CreateNoWindow = true;
string cmdtext = string.Empty;
cmdtext = "schtasks /create /tn shutdownWindows /sc DAILY /st " + app.shutdowntime + " /tr \"shutdown -s -f -t 0\" -f"; //关机
log.WriteLogFile(cmdtext, "cmdexelog");
//执行VER命令
MyProcess.Start();
MyProcess.StandardInput.WriteLine(cmdtext);
}
catch (Exception ex)
{
log.WriteLogFile(ex.ToString());
}
}
///
/// 下载应用程序
///
private void downLineExE()
{
log.WriteLogFile("开始下载");
//try
//{
// string error = "";
// //
// string filename = "";
// app.appUrl = app.appUrl.Replace("\\", "/");
// if (string.IsNullOrEmpty(app.appUrl) && (app.Appdowninfo.exestartname.IndexOf("http://") == 0 || app.Appdowninfo.exestartname.IndexOf("https://") == 0))
// {
// filename = app.Appdowninfo.exename + ".bat";
// }
// else if (app.appUrl.Contains("/"))
// filename = app.appUrl.Substring(app.appUrl.LastIndexOf("/"));
// if (string.IsNullOrEmpty(filename))
// {
// return;
// }
// string exename = app.appName;
// string path = AppDomain.CurrentDomain.BaseDirectory + "/exefile/" + filename;
// if (app.Appdowninfo.Default)
// {
// timer.Start();
// app.defaultFile = app.Appdowninfo.exename;
// }
// if (!Directory.Exists(path) || app.AppUpdate == true)
// {
// List AppList = new List();
// Class_Config config = new Class_Config();
// config.ReadAppInfo(ref AppList);
// exename = httpmessage.DownLoadexe(AppList, ref error);//正式使用下载
// IntPtr WindowAppChoose = FindWindow(null, "WindowAppChoose");
// if (WindowAppChoose != null)
// {
// SetWindowPos(WindowAppChoose, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
// SendMessage(WindowAppChoose, WM_CLOSE, 0, 0); // 调用了 发送消息 发送关闭窗口的消息
// }
// if (app.Appdowninfo.Default)
// {
// app.AppPlayName = app.Appdowninfo.exename;
// }
// //if (!string.IsNullOrEmpty(exename))
// //{
// // //下载成功
// // httpmessage.UpLoadDownLoadState(ref error, "1");
// //}
// //else
// //{
// // //下载失败
// // log.WriteLogFile(error);
// // httpmessage.UpLoadDownLoadState(ref error, "2");
// //}
// }
//}
//catch (Exception ex)
//{
// log.WriteLogFile(ex.ToString());
//}
}
private void appDown()
{
//try
//{
// if (config.RemoveExeConfig(app.AppDownCode))
// {
// Class_Config config = new Class_Config();
// config.ReadAppInfo(ref app.NowAppList);
// if (app.NowAppList == null || app.NowAppList.Count == 0)
// {
// app.configstartexe = "";
// IntPtr WindowAppChoose = FindWindow(null, "WindowAppChoose");
// if (WindowAppChoose != null || WindowAppChoose.ToString() != "0")
// {
// SetWindowPos(WindowAppChoose, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
// SendMessage(WindowAppChoose, WM_CLOSE, 0, 0); // 调用了 发送消息 发送关闭窗口的消息
// }
// IntPtr WinButton = FindWindow(null, "WindowButton");
// if (WinButton != null || WindowAppChoose.ToString() != "0")
// {
// SetWindowPos(WinButton, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
// SendMessage(WinButton, WM_CLOSE, 0, 0); // 调用了 发送消息 发送关闭窗口的消息
// }
// }
// else
// {
// var curApp = app.NowAppList.Where(i => i.AppID == app.DefaultAppCode).FirstOrDefault();
// if (curApp != null)
// {
// app.configstartexe = string.IsNullOrEmpty(curApp.exestartname) ? curApp.exepath : (curApp.exepath + "/" + curApp.exestartname);
// }
// else
// {
// app.configstartexe = "";
// }
// IntPtr WindowAppChoose = FindWindow(null, "WindowAppChoose");
// if (WindowAppChoose != null || WindowAppChoose.ToString() != "0")
// {
// SetWindowPos(WindowAppChoose, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
// SendMessage(WindowAppChoose, WM_CLOSE, 0, 0); // 调用了 发送消息 发送关闭窗口的消息
// }
// }
// log.WriteLogFile("卸载应用成功");
// }
// else
// {
// log.WriteLogFile("卸载应用失败");
// }
//}
//catch (Exception ex)
//{
// log.WriteLogFile(ex.ToString());
//}
}
///
/// 遍历文件夹判断应用程序是否存在,若存在则返回Path为打开的应用程序路径
/// 文件夹路径
/// 应用程序名称
/// 返回:应用程序路径
///
public void ListFiles(FileSystemInfo info, string name, ref string Path)
{
try
{
if (!info.Exists) return;
DirectoryInfo dir = info as DirectoryInfo;
//不是目录
if (dir == null) return;
FileSystemInfo[] files = dir.GetFileSystemInfos();
for (int i = 0; i < files.Length; i++)
{
FileInfo file = files[i] as FileInfo;
//是文件
if (file != null)
{
if (file.Name.Trim().ToLower().Equals(name))
{
Path = file.FullName;
return;
}
}
//对于子目录,进行递归调用
//else
ListFiles(files[i], name, ref Path);
}
}
catch (Exception ex)
{
log.WriteLogFile(ex.ToString());
}
}
#region Notification Icon 右下角图标事件
bool shouldClose;
WindowState lastWindowState;
protected override void OnStateChanged(EventArgs e)
{
try
{
this.lastWindowState = WindowState;
}
catch
{ }
}
protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
try
{
if (!shouldClose)
{
e.Cancel = true;
Hide();
}
}
catch { }
}
private void Open()
{
try
{
Show();
this.WindowState = WindowState.Normal;
}
catch
{ }
}
//双击还原
private void OnNotificationAreaIconDoubleClick(object sender, MouseButtonEventArgs e)
{
try
{
if (e.ChangedButton == MouseButton.Left)
{
Open();
}
}
catch
{
}
}
//re-login
private void OnReLoginClick(object sender, EventArgs e)
{
try
{
////this.Logout();
//failopen.Visibility = Visibility.Visible;
//sucessopen.Visibility = Visibility.Hidden;
//Open();
}
catch
{
}
}
private void OnMenuItemExitClick(object sender, EventArgs e)
{
try
{
this.shouldClose = true;
Close();
}
catch { }
}
#endregion
//private void Text_Focus(object sender, RoutedEventArgs e)
//{
// OpenFileDialog openExcel = new OpenFileDialog();//实例化打开对话框对象
// openExcel.Filter = "可执行文件|*.exe";//设置打开文件筛选器
// openExcel.Multiselect = false;//设置打开对话框中不能多选
// if (openExcel.ShowDialog() != System.Windows.Forms.DialogResult.OK)//判断是否选择了文件
// {
// return;
// }
// Textpath.Text = openExcel.FileName;
//}
//private void Btn_Click(object sender, RoutedEventArgs e)
//{
// StartExE(Textpath.Text.ToString());
//}
private void Btn_OK(object sender, RoutedEventArgs e)
{
this.WindowState = WindowState.Minimized;
}
#region 检测鼠标动作 设置屏保
//定义结构体
[StructLayout(LayoutKind.Sequential)]
struct LASTINPUTINFO
{
// 设置结构体块容量
[MarshalAs(UnmanagedType.U4)]
public int cbSize;
// 捕获的时间
[MarshalAs(UnmanagedType.U4)]
public uint dwTime;
}
// 定义定时器,结构体对象等
//private DispatcherTimer mIdleTimer;
private LASTINPUTINFO mLastInputInfo;
[DllImport("user32.dll")]
private static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
public static readonly IntPtr HWND_TOPMOST = new IntPtr(-1); //窗体置顶
public static readonly IntPtr HWND_NOTOPMOST = new IntPtr(-2); //取消窗体置顶
public static readonly IntPtr HWND_BOTTOM = new IntPtr(1); //取消窗体置顶
public const uint SWP_NOMOVE = 0x0002; //不调整窗体位置
public const uint SWP_NOSIZE = 0x0001; //不调整窗体大小
public enum ShowWindowCommands : int
{
SW_HIDE = 0,
SW_SHOWNORMAL = 1,
SW_NORMAL = 1,
SW_SHOWMINIMIZED = 2,
SW_SHOWMAXIMIZED = 3,
SW_MAXIMIZE = 3,
SW_SHOWNOACTIVATE = 4,
SW_SHOW = 5,
SW_MINIMIZE = 6,
SW_SHOWMINNOACTIVE = 7,
SW_SHOWNA = 8,
SW_RESTORE = 9,
SW_SHOWDEFAULT = 10,
SW_MAX = 10
}
/*初始化
mLastInputInfo = new LASTINPUTINFO();
mLastInputInfo.cbSize = Marshal.SizeOf(mLastInputInfo);
mIdleTimer = new System.Windows.Threading.DispatcherTimer();
mIdleTimer.Tick += new EventHandler(IdleTime);//起个Timer一直获取当前时间
mIdleTimer.Interval = new TimeSpan(0, 0, 0, 1, 0);
mIdleTimer.Start();
*/
bool ScreenSaver = false;
//实现 屏保开启或关闭线程
private void IdleTime(object sender, EventArgs e)
{
//if (isExecutionOpenApp)
//{
// log.WriteLogFile("正在执行打开应用操作isExecutionOpenApp", "OpenApp");
// goto DonotDone;
//}
if (GetLastInputInfo(ref mLastInputInfo))
{
//if (ConfigurationManager.AppSettings["isScreensaverOpen"].Equals("0"))
//{
if (ScreenSaver)
{
//Process[] proSc = Process.GetProcesses();
bool pcstart = false;
//for (int i = 0; i < proSc.Length; i++)
//{
// if (proSc[i].ProcessName.ToLower().Trim() == "pcscreensavers")
// {
// pcstart = true;
// }
//}
IntPtr Win = FindWindow(null, "WindowViewNew");//设置置顶
if (Win != null && Win != IntPtr.Zero)
{
pcstart = true;
//SetWindowPos(Win, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
}
if (!pcstart && !app.isStartScreen)
{
ScreenSaver = pcstart;
log.WriteLogFile("ScreenSaver =" + ScreenSaver.ToString());
}
else
{
//鼠标操作,切换应用
if ((Environment.TickCount - (long)mLastInputInfo.dwTime) / 1000 < 2)
{
log.WriteLogFile("(Environment.TickCount - (long)mLastInputInfo.dwTime) / 1000 =" + ((Environment.TickCount - (long)mLastInputInfo.dwTime) / 1000).ToString());
try
{
app.isStartScreen = false;
//关闭信息发布
Process[] pro = Process.GetProcesses();
//for (int i = 0; i < pro.Length; i++)
//{
// if (pro[i].ProcessName.ToLower().Trim() == "pcscreensavers")
// {
// pro[i].Kill();//结束进程
// }
//}
IntPtr Win1 = FindWindow(null, "WindowViewNew");//设置置顶
if (Win1 != null && Win1 != IntPtr.Zero)
{
SendMessage(Win1, WM_CLOSE, 0, 0);
app.AppPlayNameCH = "导视";
app.Appversion = app.kioskVersion;
//SetWindowPos(Win, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
}
for (int i = 0; i < pro.Length; i++)
{
if (pro[i].ProcessName.ToLower().Trim() == "screensavers")
{
pro[i].Kill();//结束进程
}
}
for (int j = 0; j < MyProcessName.Count; j++)
{
if (MyProcessName[j].Trim().ToLower().Equals("windowview"))
{
MyProcessName.RemoveAt(j);
//break;
}
}//移除进程列表中的元素
ScreenSaver = false;
app.CurAppPlayName = app.AppPlayName;
log.WriteLogFile(app.CurAppPlayName + "-----", "start");
//if (ConfigurationManager.AppSettings["MenuShow"].Equals("0")) //判断是否有悬浮框
//{
if (app.AppList != null && app.AppList.Count > 1)
{
IntPtr WinButton = FindWindow(null, "WindowButton"); //置顶窗体
if (WinButton != null && WinButton != IntPtr.Zero)
{
SetWindowPos(WinButton, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
IntPtr WinChoose = FindWindow(null, "WindowAppChoose"); //置顶窗体
if (WinChoose != null)
{
SetWindowPos(WinChoose, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
}
}
else
{
WindowButton win = new WindowButton();
win.Show();
}
}
//}
}
catch (Exception ex)
{
log.WriteLogFile(ex.ToString());
}
}
}
}
else
{
log.WriteLogFile(app.CurAppPlayName, "start");
if (!app.CurAppPlayName.Trim().ToLower().Equals("pcscreensavers"))
{
//if ((Environment.TickCount - (long)mLastInputInfo.dwTime) / 1000 > 30)
if ((Environment.TickCount - (long)mLastInputInfo.dwTime) / 1000 > app.screensaver.ScreenTime - 5) //&& (Environment.TickCount - (long)mLastInputInfo.dwTime) / 1000 < 60
{
log.WriteLogFile("(Environment.TickCount - (long)mLastInputInfo.dwTime) / 1000 =" + ((Environment.TickCount - (long)mLastInputInfo.dwTime) / 1000).ToString());
try
{
//if (ConfigurationManager.AppSettings["MenuShow"].Equals("0")) //判断是否有悬浮框
//{
log.WriteLogFile("1430行取消置顶" + app.AppList.Count);
//if(app.AppPlayinfo)
if (app.NowNeedPlayApp != null)
{
if (app.AppPlayinfo == null || app.AppPlayinfo.Name != app.NowNeedPlayApp.Name)
{
ChangeExE(app.NowNeedPlayApp.Startup, (app.HttpUrl.Replace("//", "|")).Split('/')[0].Replace("|", "//") + "|" + app.deviceid + "|" + app.configwebsocket + "|");
app.AppPlayinfo = app.NowNeedPlayApp;
}
}
else if (string.IsNullOrEmpty(app.AppPlayName))
{
killExE();
if (!string.IsNullOrEmpty(app.configstartexe))
{
ChangeExE(app.configstartexe, (app.HttpUrl.Replace("//", "|")).Split('/')[0].Replace("|", "//") + "|" + app.deviceid + "|" + app.configwebsocket + "|");
}
app.AppPlayinfo = null;
}
if (app.AppList != null && app.AppList.Count > 1)
{
IntPtr Win1 = FindWindow(null, "WindowButton"); //取消置顶
if (Win1 != null)
{
SetWindowPos(Win1, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
}
Win1 = FindWindow(null, "WindowAppChoose"); //取消置顶
if (Win1 != null)
{
SetWindowPos(Win1, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
}
//}
}
}
catch (Exception ex)
{
log.WriteLogFile(ex.ToString());
}
bool ispc = false;//pcscreensavers是否以打开
bool issc = false;//screensavers是否以打开
Process[] pro = Process.GetProcesses();
IntPtr Win = FindWindow(null, "WindowViewNew");//设置置顶
if (Win != null && Win != IntPtr.Zero)
{
ispc = true;
//SetWindowPos(Win, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
}
//for (int i = 0; i < pro.Length; i++)
//{
// if (pro[i].ProcessName.ToLower().Trim() == "pcscreensavers")
// {
// ispc = true;
// }
//}
for (int i = 0; i < pro.Length; i++)
{
if (pro[i].ProcessName.ToLower().Trim() == "screensavers")
{
issc = true;
}
}
//打开信息发布
try
{
if (!issc)
{
StartCScreen();
}
if (!ispc)
{
//string path = @"exefile\PCScreen\PCScreenSavers.exe";
//Process myprocess = new Process();
//ProcessStartInfo startInfo = new ProcessStartInfo(path, (app.HttpUrl.Replace("//", "|")).Split('/')[0].Replace("|", "//") + "|" + app.deviceid + "|" + app.configwebsocket+"|0");
//path = path.Replace("\\", "/");
//startInfo.Verb = "runas";
//startInfo.CreateNoWindow = true;
//startInfo.WorkingDirectory = path.Substring(0, path.LastIndexOf("/"));//设置应用程序在其所在目录
//myprocess.StartInfo = startInfo;
//myprocess.StartInfo.UseShellExecute = false;
//myprocess.Start();
// MyProcessName.Add(myprocess.ProcessName);
app.isStartScreen = true;
ScreenSaver = true;
//ScreenSavers result = pbm.GetResourceForLoad();
//if (result != null && result.ResList.Count > 0)
//{
// app.AppPlayNameCH = "信息发布";
// app.CurAppPlayName = "pcscreensavers";
// app.Appversion = app.Containerversion;
// MyProcessName.Add("WindowView");
WindowViewNew windowView = new WindowViewNew();
windowView.Show();
//}
}
// ScreenSaver = true;
log.WriteLogFile("打开屏保成功");
}
catch (Exception ex)
{
log.WriteLogFile("打开屏保失败" + ex.ToString());
}
}
}
}
//}
//if (app.appClick)
//{
// if ((Environment.TickCount - (long)mLastInputInfo.dwTime) / 1000 >= (app.screenTime+30))
// {
// if (!string.IsNullOrEmpty(app.NowAppName))
// {
// if (app.NowAppName != app.AppPlayinfo.Name)
// {
// //打开应用
// IEnumerable exeinfo = app.AppList.Where(i => i.Name.ToString() == app.NowAppName);
// if (exeinfo.Count() > 0)
// {
// //
// //log.WriteLogFile(exeinfo.Count().ToString());
// if (app.NowAppType != "bat" && app.NowAppType != "")
// {
// killExE();
// }
// //else if (app.NowAppType == "html")
// //{
// // app.winh5.WinClose();
// // //app.winh5 = null;
// //}
// string fileName = exeinfo.ElementAt(0).Startup;
// //if (string.IsNullOrEmpty(exeinfo.ElementAt(0).exestartname)) {
// // fileName = exeinfo.ElementAt(0).exepath;
// //} else {
// // fileName = exeinfo.ElementAt(0).exepath + "/" + exeinfo.ElementAt(0).exestartname;
// //}
// if (ChangeExE(fileName, exeinfo.ElementAt(0)))
// {
// app.AppPlayinfo = exeinfo.ElementAt(0);
// app.AppPlayNameCH = "";
// app.Appversion = "";
// }
// else
// {
// app.AppPlayName = "";
// app.AppPlayNameCH = "";
// app.Appversion = "";
// //打开失败
// }
// app.appClick = false;
// }
// }
// }
// }
//}
}
//DonotDone:
// return;
}
#endregion
[DllImport("User32.dll", EntryPoint = "SendMessage")]
public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
//关屏
[DllImport("user32.dll")]
private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);
[DllImport("shell32.dll")]
public extern static IntPtr ShellExecute(IntPtr hwnd,
string lpOperation,
string lpFile,
string lpParameters,
string lpDirectory,
int nShowCmd
);
//锁屏
[DllImport("user32.dll")]
public static extern bool LockWorkStation();
private void DevNumEdit()
{
try
{
if (config.UpdateConfig(app.devicemark))
{
log.WriteLogFile("修改设备名称成功");
}
else
{
log.WriteLogFile("修改设备名称失败");
}
}
catch (Exception ex)
{
log.WriteLogFile(ex.ToString());
}
}
private void BGSet()
{
try
{
string filefolder = AppDomain.CurrentDomain.BaseDirectory + "/bgfile";
try
{
if (!Directory.Exists(filefolder))
{
DirectoryInfo directoryInfo = new DirectoryInfo(filefolder);
directoryInfo.Create();
}
}
catch (Exception ex)
{
log.WriteLogFile(ex.ToString());
}
HttpClient httpClient = new HttpClient();
string fileName = "";
if (httpClient.DownLoadImage(app.bgPath, "bgfile", ref fileName))
{
if (app.pageBg == null)
{
app.pageBg = new BGPage();
app.pageBg.LoadImage(fileName);
app.pageBg.Show();
}
else
{
this.Dispatcher.Invoke(new Action(() =>
{
app.pageBg.LoadImage(fileName);
}));
}
//this.Dispatcher.Invoke(new Action(() =>
//{
// ADInsert adView = new ADInsert();
// adView.SetADImage(fileName, app.insertAD.Duration);
// adView.Show();
// log.WriteLogFile("插播下载成功");
//}));
//Process[] proSc = Process.GetProcesses();
//bool pcstart = false;
//for (int i = 0; i < proSc.Length; i++)
//{
// if (proSc[i].ProcessName.ToLower().Trim() == "pcscreensavers")
// {
// pcstart = true;
// break;
// }
//}
//IntPtr Win1 = FindWindow(null, "ADInsert");//设置置顶
//if (pcstart)
//{
// if (Win1 != null)
// {
// log.WriteLogFile("插播置顶:");
// SetWindowPos(Win1, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
// }
//}
//else
//{
// if (Win1 != null)
// {
// SetWindowPos(Win1, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
// }
//}
}
else
{
log.WriteLogFile("插播下载失败");
}
}
catch (Exception ex)
{
log.WriteLogFile(ex.ToString());
}
}
private void KillExplorer()
{
try
{
Process MyProcess = new Process();
//设定程序名
MyProcess.StartInfo.FileName = "cmd.exe";
//关闭Shell的使用
MyProcess.StartInfo.UseShellExecute = false;
//重定向标准输入
MyProcess.StartInfo.RedirectStandardInput = true;
//重定向标准输出
MyProcess.StartInfo.RedirectStandardOutput = true;
//重定向错误输出
MyProcess.StartInfo.RedirectStandardError = true;
MyProcess.StartInfo.CreateNoWindow = true;
MyProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;//隐藏控制台窗口
//设置不显示窗口
MyProcess.StartInfo.CreateNoWindow = true;
string cmdtext = "taskkill /im explorer.exe /t /f"; //关闭explorer(桌面进程)进程
log.WriteLogFile(cmdtext, "cmdexelog");
//执行VER命令
MyProcess.Start();
MyProcess.StandardInput.WriteLine(cmdtext);
}
catch (Exception ex)
{
log.WriteLogFile(ex.ToString());
}
}
private void StartExplorer()
{
//log.WriteLogFile(Environment.GetEnvironmentVariable("windir") + "\\explorer.exe", "explorer");
//System.Diagnostics.Process process = new System.Diagnostics.Process();
//System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
//startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
//startInfo.FileName = "cmd.exe";
//process.StartInfo = startInfo;
//process.StartInfo.RedirectStandardInput = true;
//process.StartInfo.RedirectStandardOutput = true;
//process.StartInfo.UseShellExecute = false;
//process.Start();
//process.StandardInput.WriteLine(Environment.GetEnvironmentVariable("windir") + "\\explorer.exe");
//process.StandardInput.Flush();
//process.StandardInput.Close();
//process.WaitForExit();
//ShellExecute(IntPtr.Zero, null, "explorer.exe", null, null, (int)ShowWindowCommands.SW_HIDE);
}
}
}