using log4net;
using SuperSocket.ClientEngine;
using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Timers;
using System.Windows;
namespace SolidWorksListener
{
public class Listener
{
private ILog log = LogManager.GetLogger("Listener");
private AsyncTcpSession client;
private long err_count;
private System.Timers.Timer socketTimer;
private System.Timers.Timer importTimer;
private System.Timers.Timer checkInTimer;
private volatile int is_open = int.MaxValue;
private int msgInterval = 5000;
#region 消息
public static IntPtr WTS_CURRENT_SERVER_HANDLE = IntPtr.Zero;
public void ShowMessageBox(string message, string title)
{
/*if (is_open == 0)
{
return;
}*/
is_open = 0;
int res;
WTSSendMessage(
WTS_CURRENT_SERVER_HANDLE,
WTSGetActiveConsoleSessionId(),
title, title.Length,
message, message.Length,
0, 0, out res, true);
is_open = res;
}
[DllImport("kernel32.dll", SetLastError = true)]
public static extern int WTSGetActiveConsoleSessionId();
[DllImport("wtsapi32.dll", SetLastError = true)]
public static extern bool WTSSendMessage(
IntPtr hServer,
int SessionId,
String pTitle,
int TitleLength,
String pMessage,
int MessageLength,
int Style,
int Timeout,
out int pResponse,
bool bWait);
#endregion
private void AlertMsg(string msg)
{
/// 内置WPF的 不能用
// alert.Open(msg);
/*try
{
// SwApp = (SldWorks)Marshal.GetActiveObject("SldWorks.Application.28");
var swApp = (SldWorks)System.Runtime.InteropServices.Marshal.GetActiveObject("SldWorks.Application");
swApp.SendMsgToUser2(msg, (int)swMessageBoxIcon_e.swMbStop, (int)swMessageBoxBtn_e.swMbOk);
Marshal.ReleaseComObject(swApp);
}
catch (COMException ex)
{
log.Error("Attach Sw Failed.", ex);
}*/
// WinAPI_Interop.ShowServiceMessage(msg, "提示");
// ShowMessageBox(msg, "提示");
string exeDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string alertPath = Path.GetFullPath(Path.Combine(exeDir,"..","Alert.exe"));
if (File.Exists(alertPath))
{
Process.Start(alertPath);
}
else
{
MessageBox.Show(msg, "提示");
}
/// 用MessageBox的 不能用
/*if (swApp == null)
{
int res;
WTSSendMessage(
WTS_CURRENT_SERVER_HANDLE,
WTSGetActiveConsoleSessionId(),//获得当前显示的桌面所在的SessionID
"提示", "提示".Length,
msg, msg.Length,
0, 0, out res, false);
}
else
{
swApp.SendMsgToUser2(msg, (int)swMessageBoxIcon_e.swMbStop, (int)swMessageBoxBtn_e.swMbOk);
}*/
//
///启动exe的
/*ProcessStartInfo psi = new ProcessStartInfo
{
FileName = "AlertWindow.exe",
UseShellExecute = false,
CreateNoWindow = true
};
Process process = Process.Start(psi);*/
}
public Listener()
{
client = new AsyncTcpSession();
client.Connected += Client_Connected;
client.Error += Client_Error;
client.Closed += Client_Closed;
client.DataReceived += Client_DataReceived;
log.Info("Service Started.");
}
public void Start()
{
InitSocketTimer();
}
public void Stop()
{
socketTimer?.Stop();
StopInterceptTimer();
// alert.DoClose();
// if (intercepter != null) intercepter.StopIntercept();
}
///
/// 启动Socket定时器
///
public void InitSocketTimer()
{
log.Info("Starting Socket Timer...");
socketTimer = new System.Timers.Timer(msgInterval);
socketTimer.Elapsed += Timer_Elapsed;
socketTimer.Enabled = true;
socketTimer.Start();
log.Info("Started Socket Timer!");
}
///
/// 启动金蝶拦截任务
///
public void StartInterceptTimer()
{
// if (intercepter == null) intercepter = new Intercepter(ListenImportHandle, ListenCheckInHandle);
if (importTimer == null)
{
importTimer = new System.Timers.Timer(500);
importTimer.Elapsed += ImportTimer_Elapsed;
}
importTimer.Start();
if (checkInTimer == null)
{
checkInTimer = new System.Timers.Timer(500);
checkInTimer.Elapsed += CheckInTimer_Elapsed;
}
checkInTimer.Start();
}
private void ImportTimer_Elapsed(object sender, ElapsedEventArgs e)
{
lock (importTimer)
{
ListenImportHandle();
}
}
private void CheckInTimer_Elapsed(object sender, ElapsedEventArgs e)
{
lock (checkInTimer)
{
ListenCheckInHandle();
}
}
///
/// 停止金蝶拦截任务
///
private void StopInterceptTimer()
{
/*if (intercepter != null)
{
intercepter.StopIntercept();
intercepter = null;
}*/
importTimer?.Stop();
checkInTimer?.Stop();
}
///
/// 插件返回正常时的处理
///
private void HandleNormal()
{
err_count = 0;
StopInterceptTimer();
// alert.DoHide();
}
private bool IsSwRunning()
{
Process[] ps = Process.GetProcessesByName("SLDWORKS");
bool IsRunning = (ps != null && ps.Length > 0);
log.Debug($"Sw Is Running: {IsRunning}");
return IsRunning;
}
///
/// 插件返回异常时的处理
///
private void HandleErr()
{
log.Debug($"err_count: {err_count}");
if (++err_count > 3)
{
if (IsSwRunning())
{
// 如果solidworks启动
StartInterceptTimer();
log.Debug("Ready to show Msg.");
AlertMsg("请启用插件并登录");
err_count = 3;
}
else
{
HandleNormal();
}
}
}
///
/// 搜索是否有导入窗口,有就一直最小化,并执行规则检查
///
///
private void ListenImportHandle()
{
IntPtr ptr = WindowIntPtrUtil.FindWindow(null, "Everything");//导入文档
if (ptr == IntPtr.Zero)
{
return;
}
WindowIntPtrUtil.KillProcessByIntPtr(ptr);
}
///
/// 搜索是否有检入窗口,有就一直最小化,并执行规则检查
///
///
private void ListenCheckInHandle()
{
IntPtr ptr = WindowIntPtrUtil.FindWindow(null, "检入文档");
if (ptr == IntPtr.Zero)
{
return;
}
WindowIntPtrUtil.KillProcessByIntPtr(ptr);
}
private void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
socketTimer.Stop();
try
{
if (!client.IsConnected)
{
client.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 5678));
}
else
{
var msg = Encoding.Default.GetBytes("HeatBeat");
client.Send(msg, 0, msg.Length);
}
}
catch (Exception ex)
{
HandleErr();
}
finally
{
socketTimer.Start();
}
}
///
/// 接收到消息
///
///
///
private void Client_DataReceived(object sender, DataEventArgs e)
{
byte flag = e.Data[0];
if (flag == 1)
{
HandleNormal();
}
else
{
log.Error("Plugin Return 0.");
HandleErr();
}
}
///
/// 客户端关闭,视为异常
///
///
///
private void Client_Closed(object sender, EventArgs e)
{
HandleErr();
}
///
/// 客户端异常
///
///
///
private void Client_Error(object sender, SuperSocket.ClientEngine.ErrorEventArgs e)
{
HandleErr();
}
///
/// 连接后的操作
///
///
///
private void Client_Connected(object sender, EventArgs e)
{
}
}
}