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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
using log4net;
using log4net.Appender;
using log4net.Config;
using log4net.Core;
using PdmSwPlugin.Common;
using PdmSwPlugin.Common.Setting;
using PdmSwPlugin.Main;
using PdmSwPlugin.Main.EventHandler;
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using SolidWorks.Interop.swpublished;
using SolidWorksTools;
using SolidWorksTools.File;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Windows.Forms.Integration;
 
namespace PdmSw
{
    /// <summary>
    /// ...
    /// </summary>
    [Guid("DF23E96F-A469-4302-8367-7FA2F798CD09"), ComVisible(true)]
    [SwAddin(
        Description = "SolidWorks²å¼þ",
        Title = "PdmSwPlugin",
        LoadAtStartup = true
        )]
    public partial class SwAddin : ISwAddin
    {
        static SwAddin()
        {
            // AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
            // AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += CurrentDomain_AssemblyResolve;
            /// ÉèÖÃlog4netÅäÖÃ
            string dllLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            string file = Path.Combine(dllLocation, "log4net.config");
            FileInfo info = new FileInfo(file);
            XmlConfigurator.Configure(info);
            var curPath = LogManager.GetRepository();
            var appenders = curPath.GetAppenders();
            if (appenders == null)
                return;
            foreach (var appender in appenders)
            {
                var rollingFileAppender = appender as RollingFileAppender;
                if (rollingFileAppender == null)
                    continue;
                rollingFileAppender.File = dllLocation + "/Log/";
                rollingFileAppender.ActivateOptions();
            }
        }
 
        /// <summary>
        /// ÍüÁË
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        /// <exception cref="DllNotFoundException"></exception>
        private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
        {
            string dir = new DirectoryInfo(Assembly.GetExecutingAssembly().Location).Parent.FullName;
            dir = Path.Combine(dir, @"Libs");
            if (args.Name.Contains(".resources"))
            {
                return default;
            }
            //if (AppDomain.CurrentDomain.GetAssemblies()
            //    .Where(x => !x.IsDynamic)
            //    .First(x => x.FullName == args.Name) is Assembly alreadyLoaded)
            //{
            //    return alreadyLoaded;
            //}
            string s = null;
            string name = new AssemblyName(args.Name).Name;
            foreach (var ss in Directory.EnumerateFiles(dir))
            {
                string sss = Path.GetFileNameWithoutExtension(ss);
                if (sss == name)
                {
                    s = ss;
                    break;
                }
            }
            if (s != null)
            {
                return Assembly.LoadFile(s);
            }
            throw new DllNotFoundException();
        }
 
        #region Local Variables ÊôÐÔ
 
        ICommandManager iCmdMgr = null;
        int addinID = 0;
        BitmapHandler iBmp;
 
        public const int mainCmdGroupID = 5;
        public const int mainItemID1 = 0;
        public const int mainItemID2 = 1;
        public const int mainItemID3 = 2;
        public const int flyoutGroupID = 91;
 
        /// <summary>
        /// ÉϴεĻÎĵµ
        /// </summary>
        private ModelDoc2 lastActiveDoc = null;
 
        private ILog Logger;
 
        /// <summary>
        /// ²å¼þÖ÷Ìå
        /// </summary>
        private MainControl mainControl = null;
 
        private PluginSetting GlobalConfig;
 
        #region Property Manager Variables
        UserPMPage ppage = null;
        #endregion
 
        private BaseAttacher attacher;
        private ISldWorks swApp;
        private TaskpaneView panel;
        private Form mainForm;
        // Public Properties
        public ISldWorks SwApp
        {
            get => swApp;
        }
 
        public ICommandManager CmdMgr
        {
            get { return iCmdMgr; }
        }
        #endregion
 
        #region SolidWorks Registration ×¢²á±íÏà¹Ø
        /// <summary>
        /// Ð´×¢²á±í
        /// </summary>
        /// <param name="t"></param>
        [ComRegisterFunctionAttribute]
        public static void RegisterFunction(Type t)
        {
            #region Get Custom Attribute: SwAddinAttribute »ñÈ¡³£Á¿
            SwAddinAttribute SWattr = null;
            Type type = typeof(SwAddin);
 
            foreach (System.Attribute attr in type.GetCustomAttributes(false))
            {
                if (attr is SwAddinAttribute)
                {
                    SWattr = attr as SwAddinAttribute;
                    break;
                }
            }
            #endregion
 
            try
            {
                Microsoft.Win32.RegistryKey hklm = Microsoft.Win32.Registry.LocalMachine;
                string keyId = t.GUID.ToString();
                string keyname = $"SOFTWARE\\SolidWorks\\Addins\\{{{keyId}}}";
                Microsoft.Win32.RegistryKey addinkey = hklm.CreateSubKey(keyname);
                addinkey.SetValue(null, 0);
                addinkey.SetValue("Description", SWattr.Description);
                addinkey.SetValue("Title", SWattr.Title);
 
                Microsoft.Win32.RegistryKey hkcu = Microsoft.Win32.Registry.CurrentUser;
                keyname = $"Software\\SolidWorks\\AddInsStartup\\{{{keyId}}}";
                addinkey = hkcu.CreateSubKey(keyname);
                addinkey.SetValue(null, Convert.ToInt32(SWattr.LoadAtStartup), Microsoft.Win32.RegistryValueKind.DWord);
            }
            catch (System.NullReferenceException nl)
            {
                Console.WriteLine("There was a problem registering this dll: SWattr is null. \n\"" + nl.Message + "\"");
                System.Windows.Forms.MessageBox.Show("There was a problem registering this dll: SWattr is null.\n\"" + nl.Message + "\"");
            }
 
            catch (System.Exception e)
            {
                Console.WriteLine(e.Message);
 
                System.Windows.Forms.MessageBox.Show("There was a problem registering the function: \n\"" + e.Message + "\"");
            }
        }
 
        /// <summary>
        /// É¾×¢²á±í
        /// </summary>
        /// <param name="t"></param>
        [ComUnregisterFunctionAttribute]
        public static void UnregisterFunction(Type t)
        {
            try
            {
                Microsoft.Win32.RegistryKey hklm = Microsoft.Win32.Registry.LocalMachine;
                Microsoft.Win32.RegistryKey hkcu = Microsoft.Win32.Registry.CurrentUser;
                string keyId = t.GUID.ToString();
                string keyname = $"SOFTWARE\\SolidWorks\\Addins\\{{{keyId}}}";
                hklm.DeleteSubKey(keyname);
 
                keyname = $"Software\\SolidWorks\\AddInsStartup\\{{{keyId}}}";
                hkcu.DeleteSubKey(keyname);
            }
            catch (System.NullReferenceException nl)
            {
                Console.WriteLine("There was a problem unregistering this dll: " + nl.Message);
                System.Windows.Forms.MessageBox.Show("There was a problem unregistering this dll: \n\"" + nl.Message + "\"");
            }
            catch (System.Exception e)
            {
                Console.WriteLine("There was a problem unregistering this dll: " + e.Message);
                System.Windows.Forms.MessageBox.Show("There was a problem unregistering this dll: \n\"" + e.Message + "\"");
            }
        }
 
        #endregion
 
        #region ISwAddin Implementation ²å¼þ¾ßÌåʵÏÖ
        public SwAddin()
        {
            Logger = BaseAttacher.Logger;
            // Çл»ÅäÖÃÎļþµØÖ·
            // ChangeAppConfig();
            GlobalConfig = PluginSetting.Instance;
        }
 
        public bool ConnectToSW(object ThisSW, int cookie)
        {
            swApp = (ISldWorks)ThisSW;
            addinID = cookie;
 
            //Setup callbacks
            SwApp.SetAddinCallbackInfo2(0, this, addinID);
 
            #region Setup the Command Manager
            iCmdMgr = SwApp.GetCommandManager(cookie);
            // AddCommandMgr();
            #endregion
 
            // ¼ÓÔØ²å¼þ
            SetPlugins();
 
            attacher = new BaseAttacher(swApp, mainControl);
            attacher.AttachEventHandlers();
 
            #region Setup Sample Property Manager
            AddPMP();
            #endregion
 
            // GlobalExceptionHandler();
 
            //LoadPlugins();
            return true;
        }
 
        private void SetPlugins()
        {
            // ¶Áͼ£¬¹À¼ÆÊÇpanelµÄͼ±ê
            string location = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            string imageFolder = Path.Combine(location, @"Images");
            string[] bitmaps = new string[]
            {
                    Path.Combine(imageFolder, @"MatChooser_20X20.png"),
                    Path.Combine(imageFolder, @"MatChooser_32X32.png"),
                    Path.Combine(imageFolder, @"MatChooser_40X40.png"),
                    Path.Combine(imageFolder, @"MatChooser_64X64.png"),
                    Path.Combine(imageFolder, @"MatChooser_96X96.png"),
                    Path.Combine(imageFolder, @"MatChooser_128X128.png")
            };
            // ´´½¨Panel
            panel = SwApp.CreateTaskpaneView3(bitmaps, "PdmSwPlugin" + PluginConst.Version);
 
            mainControl = new MainControl((SldWorks)SwApp);
            // Ö»ÄÜÓÃwinform£¬´úÀíwpf
            ElementHost host = new ElementHost
            {
                Child = mainControl,
                AutoSize = true,
                Dock = DockStyle.Fill
            };
            mainForm = new Form
            {
                Text = "PdmSwPlugin",
                ControlBox = false,
                FormBorderStyle = FormBorderStyle.None,
                KeyPreview = true,
                Dock = DockStyle.Fill
            };
            mainForm.FormClosed += MainForm_FormClosed;
            mainForm.Controls.Add(host);
            IntPtr ptr = mainForm.Handle;
            // IntPtr ptr = WindowIntPtrUtil.FindWindow(null, "Window1");
            panel.DisplayWindowFromHandlex64(ptr.ToInt64());
            mainForm.WindowState = FormWindowState.Maximized;
        }
 
        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            /// ¹Ø±ÕʱÏÈÖ´ÐÐDeActiveHandler£¬È»ºóÖ´ÐÐÕâ¸ö
            
        }
 
        private void LoadPlugins()
        {
            // ¶Áͼ£¬¹À¼ÆÊÇpanelµÄͼ±ê
            string location = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            string imageFolder = Path.Combine(location, @"Images");
            string[] bitmaps = new string[]
            {
                    Path.Combine(imageFolder, @"MatChooser_20X20.png"),
                    Path.Combine(imageFolder, @"MatChooser_32X32.png"),
                    Path.Combine(imageFolder, @"MatChooser_40X40.png"),
                    Path.Combine(imageFolder, @"MatChooser_64X64.png"),
                    Path.Combine(imageFolder, @"MatChooser_96X96.png"),
                    Path.Combine(imageFolder, @"MatChooser_128X128.png")
            };
            // ´´½¨Panel
            TaskpaneView panel = SwApp.CreateTaskpaneView3(bitmaps, "ÎïÁϲéѯ" + PluginConst.Version);
 
            PluginLoader pl = new PluginLoader("ms");
            long res = (long)pl.ExecuteMothod("PdmSwPlugin.MaterialSelect.MaterialSelectControl", "GetWindowHandle",
                new object[] { (SldWorks)SwApp });
            panel.DisplayWindowFromHandlex64(res);
        }
 
        /// <summary>
        /// ¶Ï¿ªÓëSolidWorksÁ¬½Ó
        /// </summary>
        /// <returns></returns>
        public bool DisconnectFromSW()
        {
            try
            {
                RemoveCommandMgr();
                RemovePMP();
                mainControl.StopTcpServer();
                mainControl.DeActiveHandler();
                attacher.DetachEventHandlers();
                attacher = null;
 
                mainForm.Close();
                mainForm = null;
                mainControl = null;
                panel.DeleteView();
                panel = null;
 
                Marshal.ReleaseComObject(iCmdMgr);
                iCmdMgr = null;
                Marshal.ReleaseComObject(SwApp);
                swApp = null;
                //The addin _must_ call GC.Collect() here in order to retrieve all managed code pointers 
                GC.Collect();
                GC.WaitForPendingFinalizers();
 
                //GC.Collect();
                //GC.WaitForPendingFinalizers();
            }
            catch (Exception ex)
            {
                Logger.Error("DisconnectFromSW Failed!", ex);
            }
            return true;
        }
        #endregion
 
        #region Ä£°å×Ô´øµÄÓò»µ½µÄ·½·¨£¬±ðɾÍòÒ»ÓÐÓÃ
        #region UI Methods
        public void AddCommandMgr()
        {
            ICommandGroup cmdGroup;
            if (iBmp == null)
                iBmp = new BitmapHandler();
            Assembly thisAssembly;
            int cmdIndex0, cmdIndex1;
            string Title = "LHJ²å¼þ", ToolTip = "LHJ²å¼þ";
 
 
            int[] docTypes = new int[]{(int)swDocumentTypes_e.swDocASSEMBLY,
                                       (int)swDocumentTypes_e.swDocDRAWING,
                                       (int)swDocumentTypes_e.swDocPART};
 
            thisAssembly = System.Reflection.Assembly.GetAssembly(this.GetType());
 
 
            int cmdGroupErr = 0;
            bool ignorePrevious = false;
 
            object registryIDs;
            //get the ID information stored in the registry
            bool getDataResult = iCmdMgr.GetGroupDataFromRegistry(mainCmdGroupID, out registryIDs);
 
            int[] knownIDs = new int[2] { mainItemID1, mainItemID2 };
 
            if (getDataResult)
            {
                if (!CompareIDs((int[])registryIDs, knownIDs)) //if the IDs don't match, reset the commandGroup
                {
                    ignorePrevious = true;
                }
            }
 
            cmdGroup = iCmdMgr.CreateCommandGroup2(mainCmdGroupID, Title, ToolTip, "", -1, ignorePrevious, ref cmdGroupErr);
            cmdGroup.LargeIconList = iBmp.CreateFileFromResourceBitmap("PdmSw.Images.ToolbarLarge.bmp", thisAssembly);
            cmdGroup.SmallIconList = iBmp.CreateFileFromResourceBitmap("PdmSw.Images.ToolbarSmall.bmp", thisAssembly);
            cmdGroup.LargeMainIcon = iBmp.CreateFileFromResourceBitmap("PdmSw.Images.MainIconLarge.bmp", thisAssembly);
            cmdGroup.SmallMainIcon = iBmp.CreateFileFromResourceBitmap("PdmSw.Images.MainIconSmall.bmp", thisAssembly);
 
            int menuToolbarOption = (int)(swCommandItemType_e.swMenuItem | swCommandItemType_e.swToolbarItem);
            cmdIndex0 = cmdGroup.AddCommandItem2("CreateCube", -1, "Create a cube", "Create cube", 0, "CreateCube", "", mainItemID1, menuToolbarOption);
            cmdIndex1 = cmdGroup.AddCommandItem2("Show PMP", -1, "Display sample property manager", "Show PMP", 2, "ShowPMP", "EnablePMP", mainItemID2, menuToolbarOption);
 
            cmdGroup.HasToolbar = true;
            cmdGroup.HasMenu = true;
            cmdGroup.Activate();
 
            bool bResult;
 
 
 
            FlyoutGroup flyGroup = iCmdMgr.CreateFlyoutGroup(flyoutGroupID, "Dynamic Flyout", "Flyout Tooltip", "Flyout Hint",
              cmdGroup.SmallMainIcon, cmdGroup.LargeMainIcon, cmdGroup.SmallIconList, cmdGroup.LargeIconList, "FlyoutCallback", "FlyoutEnable");
 
 
            flyGroup.AddCommandItem("FlyoutCommand 1", "test", 0, "FlyoutCommandItem1", "FlyoutEnableCommandItem1");
 
            flyGroup.FlyoutType = (int)swCommandFlyoutStyle_e.swCommandFlyoutStyle_Simple;
 
 
            foreach (int type in docTypes)
            {
                CommandTab cmdTab;
 
                cmdTab = iCmdMgr.GetCommandTab(type, Title);
 
                if (cmdTab != null & !getDataResult | ignorePrevious)//if tab exists, but we have ignored the registry info (or changed command group ID), re-create the tab.  Otherwise the ids won't matchup and the tab will be blank
                {
                    bool res = iCmdMgr.RemoveCommandTab(cmdTab);
                    cmdTab = null;
                }
 
                //if cmdTab is null, must be first load (possibly after reset), add the commands to the tabs
                if (cmdTab == null)
                {
                    cmdTab = iCmdMgr.AddCommandTab(type, Title);
 
                    CommandTabBox cmdBox = cmdTab.AddCommandTabBox();
 
                    int[] cmdIDs = new int[3];
                    int[] TextType = new int[3];
 
                    cmdIDs[0] = cmdGroup.get_CommandID(cmdIndex0);
 
                    TextType[0] = (int)swCommandTabButtonTextDisplay_e.swCommandTabButton_TextHorizontal;
 
                    cmdIDs[1] = cmdGroup.get_CommandID(cmdIndex1);
 
                    TextType[1] = (int)swCommandTabButtonTextDisplay_e.swCommandTabButton_TextHorizontal;
 
                    cmdIDs[2] = cmdGroup.ToolbarId;
 
                    TextType[2] = (int)swCommandTabButtonTextDisplay_e.swCommandTabButton_TextHorizontal | (int)swCommandTabButtonFlyoutStyle_e.swCommandTabButton_ActionFlyout;
 
                    bResult = cmdBox.AddCommands(cmdIDs, TextType);
 
 
 
                    CommandTabBox cmdBox1 = cmdTab.AddCommandTabBox();
                    cmdIDs = new int[1];
                    TextType = new int[1];
 
                    cmdIDs[0] = flyGroup.CmdID;
                    TextType[0] = (int)swCommandTabButtonTextDisplay_e.swCommandTabButton_TextBelow | (int)swCommandTabButtonFlyoutStyle_e.swCommandTabButton_ActionFlyout;
 
                    bResult = cmdBox1.AddCommands(cmdIDs, TextType);
 
                    cmdTab.AddSeparator(cmdBox1, cmdIDs[0]);
 
                }
 
            }
            thisAssembly = null;
 
        }
 
        public void RemoveCommandMgr()
        {
            iBmp?.Dispose();
            iCmdMgr?.RemoveCommandGroup(mainCmdGroupID);
            iCmdMgr?.RemoveFlyoutGroup(flyoutGroupID);
        }
 
        public bool CompareIDs(int[] storedIDs, int[] addinIDs)
        {
            List<int> storedList = new List<int>(storedIDs);
            List<int> addinList = new List<int>(addinIDs);
 
            addinList.Sort();
            storedList.Sort();
 
            if (addinList.Count != storedList.Count)
            {
                return false;
            }
            else
            {
 
                for (int i = 0; i < addinList.Count; i++)
                {
                    if (addinList[i] != storedList[i])
                    {
                        return false;
                    }
                }
            }
            return true;
        }
 
        public Boolean AddPMP()
        {
            ppage = new UserPMPage(this);
            return true;
        }
 
        public Boolean RemovePMP()
        {
            ppage = null;
            return true;
        }
 
        #endregion
 
        #region UI Callbacks
        public void CreateCube()
        {
            System.Windows.Forms.MessageBox.Show("There is no part template available. Please check your options and make sure there is a part template selected, or select a new part template.");
        }
 
 
        public void ShowPMP()
        {
            if (ppage != null)
                ppage.Show();
        }
 
        public int EnablePMP()
        {
            if (SwApp.ActiveDoc != null)
                return 1;
            else
                return 0;
        }
 
        public void FlyoutCallback()
        {
            FlyoutGroup flyGroup = iCmdMgr.GetFlyoutGroup(flyoutGroupID);
            flyGroup.RemoveAllCommandItems();
 
            flyGroup.AddCommandItem(System.DateTime.Now.ToLongTimeString(), "test", 0, "FlyoutCommandItem1", "FlyoutEnableCommandItem1");
 
        }
        public int FlyoutEnable()
        {
            return 1;
        }
 
        public void FlyoutCommandItem1()
        {
            SwApp.SendMsgToUser("Flyout command 1");
        }
 
        public int FlyoutEnableCommandItem1()
        {
            return 1;
        }
        #endregion
        #endregion
    }
 
}