chr
7 天以前 43a0207d207390abdeeb3ab9155eebf03edd7b1a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
using log4net;
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using SuperSocket.ClientEngine;
using System;
using System.Diagnostics;
using System.Net;
using System.Runtime.InteropServices;
using System.ServiceProcess;
using System.Text;
using System.Timers;
using System.Windows;
using Test1;
 
namespace PluginListener
{
    public class Listener : ServiceBase
    {
        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 Alert alert;
        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
 
 
        #region 组件设计器生成的代码
        /// <summary> 
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;
 
        /// <summary>
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }
 
        /// <summary> 
        /// 设计器支持所需的方法 - 不要修改
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            components = new System.ComponentModel.Container();
            this.ServiceName = "PdmSwPluginLisener";
            this.CanStop = true;
        }
        #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, "提示");
 
            /// 用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()
        {
            alert = new Alert();
            client = new AsyncTcpSession();
            client.Connected += Client_Connected;
            client.Error += Client_Error;
            client.Closed += Client_Closed;
            client.DataReceived += Client_DataReceived;
            InitializeComponent();
            log.Info("Service Started.");
        }
 
        protected override void OnStart(string[] args)
        {
            Start();
        }
 
        protected override void OnStop()
        {
            Stop();
        }
 
        public void Start()
        {
            InitSocketTimer();
        }
 
        public void Stop()
        {
            socketTimer?.Stop();
            StopInterceptTimer();
            // alert.DoClose();
            // if (intercepter != null) intercepter.StopIntercept();
        }
 
        /// <summary>
        /// 启动Socket定时器
        /// </summary>
        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!");
        }
 
        /// <summary>
        /// 启动金蝶拦截任务
        /// </summary>
        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();
            }
        }
 
        /// <summary>
        /// 停止金蝶拦截任务
        /// </summary>
        private void StopInterceptTimer()
        {
            /*if (intercepter != null)
            {
                intercepter.StopIntercept();
                intercepter = null;
            }*/
            importTimer?.Stop();
            checkInTimer?.Stop();
        }
 
        /// <summary>
        /// 插件返回正常时的处理
        /// </summary>
        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;
        }
 
        /// <summary>
        /// 插件返回异常时的处理
        /// </summary>
        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();
                }
            }
        }
 
 
        /// <summary>
        /// 搜索是否有导入窗口,有就一直最小化,并执行规则检查
        /// </summary>
        /// <returns></returns>
        private void ListenImportHandle()
        {
            IntPtr ptr = WindowIntPtrUtil.FindWindow(null, "Everything");//导入文档
            if (ptr == IntPtr.Zero)
            {
                return;
            }
            WindowIntPtrUtil.KillProcessByIntPtr(ptr);
        }
 
        /// <summary>
        /// 搜索是否有检入窗口,有就一直最小化,并执行规则检查
        /// </summary>
        /// <returns></returns>
        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();
            }
        }
 
        /// <summary>
        /// 接收到消息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Client_DataReceived(object sender, DataEventArgs e)
        {
            byte flag = e.Data[0];
            if (flag == 1)
            {
                HandleNormal();
            }
            else
            {
                log.Error("Plugin Return 0.");
                HandleErr();
            }
        }
 
        /// <summary>
        /// 客户端关闭,视为异常
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Client_Closed(object sender, EventArgs e)
        {
            HandleErr();
        }
 
        /// <summary>
        /// 客户端异常
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Client_Error(object sender, ErrorEventArgs e)
        {
            HandleErr();
        }
 
        /// <summary>
        /// 连接后的操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Client_Connected(object sender, EventArgs e)
        {
 
        }
    }
}