/[DXTViewerLoader]/trunk/DXTViewerLoader/DXTViewer.cs
ViewVC logotype

Contents of /trunk/DXTViewerLoader/DXTViewer.cs

Parent Directory Parent Directory | Revision Log Revision Log


Revision 8 - (show annotations) (download)
Thu Dec 12 11:55:39 2013 UTC (6 years, 2 months ago) by william
File size: 41203 byte(s)

1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Diagnostics;
6 using System.Windows.Forms;
7 using System.IO;
8 using System.Runtime.InteropServices;
9 using System.Collections;
10 using System.Drawing;
11 using System.Threading;
12 using System.Xml.Linq;
13 using Enterprise.Logging;
14
15 namespace DXTViewerLoader
16 {
17 internal static class DXTViewer
18 {
19 #region Win32Api
20 [StructLayout(LayoutKind.Sequential)]
21 struct RECT
22 {
23 public int left, top, right, bottom;
24 public RECT(Point location, Size size) : this(new Rectangle(location, size)) { }
25 public RECT(int x, int y, int width, int height) : this(new Rectangle(x, y, width, height)) { }
26 public RECT(Rectangle r)
27 {
28 left = r.Left;
29 top = r.Top;
30 right = r.Right;
31 bottom = r.Bottom;
32 }
33 }
34 [StructLayout(LayoutKind.Sequential)]
35 public struct POINT
36 {
37 public int X;
38 public int Y;
39
40 public POINT(int x, int y)
41 {
42 this.X = x;
43 this.Y = y;
44 }
45
46 public static implicit operator System.Drawing.Point(POINT p)
47 {
48 return new System.Drawing.Point(p.X, p.Y);
49 }
50
51 public static implicit operator POINT(System.Drawing.Point p)
52 {
53 return new POINT(p.X, p.Y);
54 }
55 }
56
57 private static IntPtr MakeLParam(int LoWord, int HiWord)
58 {
59 return (IntPtr)((HiWord << 16) | (LoWord & 0xffff));
60 }
61 const uint WM_KEYDOWN = 0x100;
62 const uint WM_KEYUP = 0x101;
63 const uint WM_CHAR = 0x102;
64 const uint WM_PAINT = 0xF;
65
66 const int VK_MENU = 0x12;
67
68 static bool RefreshWindow(IntPtr hWnd) { return RefreshWindow(hWnd, IntPtr.Zero, false); }
69 static bool RefreshWindow(IntPtr hWnd, IntPtr lpRect, bool bErase)
70 {
71 if (!InvalidateRect(hWnd, lpRect, bErase))
72 {
73 gLog.Error.WriteLine("An Error ocurred while calling: InvalidateRect on handle: 0x{0:x8}", hWnd.ToInt32());
74 return false;
75 }
76 if (!UpdateWindow(hWnd))
77 {
78 gLog.Error.WriteLine("An Error ocurred while calling: UpdateWindow on handle: 0x{0:x8}", hWnd.ToInt32());
79 return false;
80 }
81 return true;
82 }
83
84 ////public static void sendKey(IntPtr hwnd, char key, bool extended)
85 ////{
86 //// PostMessage(hwnd, WM_CHAR, (IntPtr)key, (IntPtr)0);
87 ////}
88 //public static void sendKey(IntPtr hwnd, char key, bool extended)
89 //{
90 // //uint scanCode = MapVirtualKey((uint)key, 0);
91 // uint lParam;
92 // //KEY DOWN
93 // lParam = (0x00000001);// | (scanCode << 16));
94 // if (extended)
95 // {
96 // lParam = lParam | 0x01000000;
97 // }
98 // PostMessage(hwnd, WM_KEYDOWN, (IntPtr)key, (IntPtr)lParam);
99 // //PostMessage(hwnd, (UInt32)WM_KEYUP, (IntPtr)key, (IntPtr)lParam);
100 //}
101 [DllImport("user32.dll")]
102 static extern bool InvalidateRect(IntPtr hWnd, IntPtr lpRect, bool bErase);
103 [DllImport("user32.dll")]
104 static extern bool UpdateWindow(IntPtr hWnd);
105
106 [DllImport("user32.dll")]
107 static extern byte VkKeyScan(char ch);
108
109 [DllImport("user32.dll")]
110 static extern uint MapVirtualKey(uint uCode, uint uMapType);
111
112 [return: MarshalAs(UnmanagedType.Bool)]
113 [DllImport("user32.dll", SetLastError = true)]
114 static extern bool PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
115
116 [DllImport("user32.dll", EntryPoint = "SendMessage")]
117 private static extern IntPtr SendMessage(IntPtr hWnd, UInt32 msg, IntPtr wParam, IntPtr lParam);
118 [DllImport("user32.dll", CharSet = CharSet.Auto)]
119 static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, StringBuilder lParam);
120 //If you use '[Out] StringBuilder', initialize the string builder with proper length first.
121
122 [DllImport("user32.dll", EntryPoint = "SendMessage")]
123 static extern IntPtr SendMessage(IntPtr hWnd, UInt32 msg, IntPtr wParam, ref RECT lParam);
124 [DllImport("user32.dll", EntryPoint = "SendMessage")]
125 static extern IntPtr SendMessage(IntPtr hWnd, UInt32 msg, IntPtr wParam, ref POINT lParam);
126 [DllImport("user32.dll", EntryPoint = "SendMessage")]
127 static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, Int32 wParam, Int32 lParam);
128 /*
129 // Select All
130 SendMessage(listBox.Handle, 0x185, (IntPtr)1, (IntPtr)(-1));
131 // Unselect All
132 SendMessage(listBox.Handle, 0x185, (IntPtr)0, (IntPtr)(-1));
133 */
134
135
136 [DllImport("user32.dll")]
137 public static extern bool SetForegroundWindow(IntPtr hWnd);
138
139 [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
140 private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
141 [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
142 private static extern int GetWindowTextLength(IntPtr hWnd);
143
144 [DllImport("user32.dll", SetLastError = true)]
145 static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
146 private delegate bool EnumedWindow(IntPtr handleWindow, ArrayList handles);
147 [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
148 [return: MarshalAs(UnmanagedType.Bool)]
149 private static extern bool EnumWindows(EnumedWindow lpEnumFunc, ArrayList lParam);
150
151 [DllImport("user32")]
152 [return: MarshalAs(UnmanagedType.Bool)]
153 private static extern bool EnumChildWindows(IntPtr window, EnumedWindow callback, ArrayList lParam);
154 private static bool GetWindowHandle(IntPtr windowHandle, ArrayList windowHandles)
155 {
156 windowHandles.Add(windowHandle);
157 return true;
158 }
159 #endregion
160 internal interface IInitializationParameters
161 {
162 string TargetImage { get; set; }
163 string ToString();
164 }
165 internal class InitializationParameters : IInitializationParameters
166 {
167 public InitializationParameters() : this(string.Empty) { }
168 public InitializationParameters(string image) { this.TargetImage = image; }
169 [Obsolete("This tool will only load one image ... any extras will be ignored",false)]
170 public InitializationParameters(List<string> images) : this(images == null || images.Count == 0 ? string.Empty : images.First()) { }
171 #region IInitializationParameters
172 public String TargetImage { get; set; }
173 #endregion
174 public override string ToString()
175 {
176 StringBuilder builder = new StringBuilder();
177 if (TargetImage == string.Empty)
178 {
179 builder.AppendLine("\tTargetImage: none");
180 }
181 else
182 {
183 builder.AppendLine(string.Format("TargetImage:{0}", TargetImage));
184 }
185 return builder.ToString();
186 }
187 }
188 internal static class Consts
189 {
190 #if DEV_DEBUG
191 internal const string dxtviewer_exe = @"C:\Program Files (x86)\oZone3D\DXTViewer\DXTViewer.exe";
192 #else
193 internal const string dxtviewer_exe="";
194 #endif
195 #if DEV_DEBUG
196 internal const string dxtviewer_window_title = "DXTViewer - Compressed Texture Viewer - www.oZone3D.Net";
197 #else
198 internal const string dxtviewer_window_title="";
199 #endif
200 #if DEV_DEBUG
201 internal const string dxtviewer_openfiledialog_title = "Load an RGB Byte Image";
202 #else
203 internal const string dxtviewer_openfiledialog_title="";
204 #endif
205 //internal const string ProcessName = "DXTViewer";
206 internal static string ProcessExecutable
207 {
208 get { return string.Format("{0}", dxtviewer_exe); }
209 }
210 internal const string ConfigName = "DXTViewer.xml";
211 }
212
213 #region Internal Helpers
214 private static string APP_PATH
215 {
216 get { return Application.StartupPath; }
217 }
218 private static string GetConfigparameter(string name)
219 {
220 try
221 {
222 FileInfo fi = GetConfig();
223 XDocument doc = XDocument.Load(fi.FullName);
224 if (doc.Descendants(name).Count() == 0)
225 {
226 gLog.Debug.WriteLine("Could not find config option: {0}", name);
227 throw new Exceptions.ConfigParameterNotFoundException(true, name);
228 }
229 var config_option = doc.Descendants(name).First();
230 if (config_option.Attributes().Count() == 0)
231 {
232
233 gLog.Debug.WriteLine("Found config option: {0} but it does not have any attributes", name);
234 throw new Exceptions.ConfigParameterNotFoundException(true, name);
235 }
236 else
237 {
238 if (config_option.Attributes("value").Count() == 0)
239 {
240 gLog.Debug.WriteLine("Found config option: {0} but it does not have a 'value' attribute", name);
241 throw new Exceptions.ConfigParameterNotFoundException(true, name);
242 }
243 else
244 {
245 var config_value = config_option.Attributes("value").First();
246
247 if (config_value.Value == string.Empty)
248 {
249 gLog.Debug.WriteLine("Found config option: {0} but it was an empty string", name);
250 throw new Exceptions.ConfigParameterNotFoundException(true, name);
251 }
252 else
253 {
254 return config_value.Value;
255 }
256 }
257 }
258 }
259 catch (Exception ex)
260 {
261 throw ex;
262 }
263 }
264 #endregion
265
266 private static IInitializationParameters InitParams
267 {
268 get;
269 set;
270 }
271 internal static void Initialize() { Initialize(new InitializationParameters()); }
272 internal static void Initialize(IInitializationParameters parameters)
273 {
274 InitParams = parameters;
275 gLog.Debug.WriteLine("InitParams:");
276 gLog.Debug.WriteLine(InitParams.ToString());
277 StartProcess();
278 }
279 #region GetProcess()
280 //private static Process GetProcess(bool DisplayError)
281 //{
282 // var procs = Process.GetProcessesByName(Consts.ProcessName);
283 // //var proc = procs.FirstOrDefault();
284 // var proc = procs[0];
285 // if (proc == null) { throw new Exceptions.ProcessInstanceNotFoundException(DisplayError); }
286 // return proc;
287 //}
288 //internal static Process GetProcess()
289 //{
290 // return GetProcess(true);
291 //}
292 #endregion
293
294 #region GetConfig()
295 internal static FileInfo GetConfig()
296 {
297 FileInfo fi = new FileInfo(string.Format(@"{0}\{1}", APP_PATH, Consts.ConfigName));
298 if (!fi.Exists) { throw new Exceptions.ConfigNotFoundException(true); }
299 else { return fi; }
300 }
301 #endregion
302
303 #region GetModule()
304 private static FileInfo GetModule(string path)
305 {
306 FileInfo fi = null;
307 if (path == string.Empty)
308 {
309 try
310 {
311 string t_path = GetConfigparameter("dxtviewer_exe");
312 if (string.IsNullOrEmpty(t_path))
313 {
314 string path_missing_message = string.Format("Config: '{0}' is either missing the 'path' parameter or it has not been configured.", Consts.ConfigName);
315 gLog.Warn.WriteLine(path_missing_message);
316 Exception path_missing = new Exception(path_missing_message);
317 throw path_missing;
318 }
319 #if !DEV_DEBUG
320 Consts.dxtviewer_exe = t_path;
321 #endif
322 fi = new FileInfo(string.Format(@"{0}", Consts.ProcessExecutable));
323 gLog.Info.WriteLine("Using '{0}' from: {1}", Consts.ProcessExecutable, fi.FullName);
324 }
325 catch (Exception ex)
326 {
327 throw new Exceptions.ModuleNotFoundException(true, ex);
328 }
329 }
330 else
331 {
332 #if !DEV_DEBUG
333 string t_path = GetConfigparameter("dxtviewer_exe");
334 Consts.dxtviewer_exe = t_path;
335 #endif
336 fi = new FileInfo(string.Format(@"{0}", Consts.ProcessExecutable));
337 gLog.Info.WriteLine("Using '{0}' from: {1}", Consts.ProcessExecutable, fi.FullName);
338 }
339 return fi;
340 }
341 private static FileInfo GetModule()
342 {
343 #if DEV_DEBUG
344 return GetModule(Consts.dxtviewer_exe);
345 #else
346 return GetModule(string.Empty);
347 #endif
348 }
349
350 //private static bool IsRunning(out Process proc)
351 //{
352 // proc = null;
353 // try
354 // {
355 // proc = GetProcess(false);
356 // return true;
357 // }
358 // catch (Exception) { return false; }
359 //}
360 //private static bool IsRunning()
361 //{
362 // Process p = null;
363 // return IsRunning(out p);
364 //}
365 private static Process _instance;
366 internal static Process Instance
367 {
368 get
369 {
370 return _instance;
371 }
372 private set { _instance = value; }
373 }
374
375 private static void StartProcess()
376 {
377 // determine if process is running
378 try
379 {
380 //if (InitParams.TargetPlugins.Count == 0)
381 //{
382 // gLog.Warn.WriteLine("No plugins have been selected for editing...exiting");
383 // return;
384 //}
385 Process p = null;
386 #if !ALWAYS_START_NEW_PROCESS_INSTANCE
387 if (IsRunning(out p))
388 {
389 gLog.Debug.WriteLine("{0} is already running: id=0x{1:x8} windowhandle=0x{2:x8}", p.ProcessName, p.Id, p.MainWindowHandle.ToInt32());
390 Instance = p;
391 return;
392 }
393 else
394 {
395 #endif
396 FileInfo module = GetModule();
397 #if ALWAYS_START_NEW_PROCESS_INSTANCE
398 gLog.Debug.Write("staring new instance of {0}...", module.FullName);
399 #else
400 gLog.Debug.Write("{0} not running staring new instance...", module.FullName);
401 #endif
402 p = new Process();
403 p.StartInfo.FileName = module.FullName;
404 p.StartInfo.Arguments = string.Empty;
405 p.StartInfo.UseShellExecute = false;
406 p.StartInfo.WorkingDirectory = module.Directory.FullName;
407 p.Start();
408 while (p.MainWindowHandle == IntPtr.Zero)
409 {
410 Application.DoEvents();
411 }
412 gLog.Debug.WriteLine("id=0x{0:x8} windowhandle=0x{1:x8} ", p.Id, p.MainWindowHandle.ToInt32());
413 Instance = p;
414 WaitForWindowInitialization();
415 return;
416 #if !ALWAYS_START_NEW_PROCESS_INSTANCE
417 }
418 #endif
419 }
420 catch (Exception ex)
421 {
422 throw new Exceptions.UnableToStartProcessException(true, ex);
423 }
424 }
425
426 #endregion
427
428
429 #region DoWork()
430 private static void WaitForWindowInitialization()
431 {
432 var windowHandles = new ArrayList();
433 EnumedWindow callBackPtr = GetWindowHandle;
434 //string lookup_title = Consts.PluginSelectionWindowTile;
435 #if !DEV_DEBUG
436 var t = GetConfigparameter("dxtviewer_window_title");
437 Consts.dxtviewer_window_title = t;
438 #endif
439 string found_title = "";
440 while (found_title != Consts.dxtviewer_window_title)
441 {
442 if (!EnumWindows(callBackPtr, windowHandles))
443 {
444 gLog.Error.WriteLine("Failed to enumerate windows...");
445 return;
446 }
447 else
448 {
449 foreach (IntPtr windowhandle in windowHandles)
450 {
451 try
452 {
453 uint pid = 0;
454 GetWindowThreadProcessId(windowhandle, out pid);
455 int length = GetWindowTextLength(windowhandle);
456 StringBuilder windowTitle = new StringBuilder(length + 1);
457 GetWindowText(windowhandle, windowTitle, windowTitle.Capacity);
458 if (windowTitle.ToString() == Consts.dxtviewer_window_title && pid == Instance.Id)
459 {
460 found_title = windowTitle.ToString();
461 break;
462 }
463 }
464 catch (Exception ex)
465 {
466 gLog.Error.WriteLine(ex.ToString());
467 }
468
469
470 }
471 }
472 }
473 }
474 internal static void DoWork()
475 {
476 if (Instance == null)// && InitParams.TargetPlugins.Count > 0)
477 {
478 NullReferenceException ex = new NullReferenceException("DXTViewer Instance is null, did you call Initialize()?");
479 gLog.Error.WriteLine(ex.ToString());
480 throw ex;
481 }
482 //if (InitParams.TargetPlugins.Count == 0) { return; }
483 #if !DEV_DEBUG
484 var t = GetConfigparameter("dxtviewer_window_title");
485 Consts.dxtviewer_window_title = t;
486 #endif
487 List<IntPtr> WindowHandles = new List<IntPtr>();
488 var windowHandles = new ArrayList();
489 EnumedWindow callBackPtr = GetWindowHandle;
490
491 if (!EnumWindows(callBackPtr, windowHandles))
492 {
493 gLog.Error.WriteLine("Failed to enumerate windows...");
494 return;
495 }
496 else
497 {
498 foreach (IntPtr windowhandle in windowHandles)
499 {
500 try
501 {
502 uint pid = 0;
503 GetWindowThreadProcessId(windowhandle, out pid);
504
505 int length = GetWindowTextLength(windowhandle);
506 StringBuilder windowTitle = new StringBuilder(length + 1);
507 GetWindowText(windowhandle, windowTitle, windowTitle.Capacity);
508 GetWindowThreadProcessId(windowhandle, out pid);
509 if (windowTitle.ToString() == Consts.dxtviewer_window_title && pid == Instance.Id)
510 {
511 WindowHandles.Add(windowhandle);
512 gLog.Debug.WriteLine("Process: {0} (id=0x{1:x8} windowhandle=0x{2:x8}) title='{3}'", Consts.ProcessExecutable, pid, windowhandle.ToInt32(), windowTitle);
513 //break;
514 }
515 }
516 catch (Exception ex)
517 {
518 gLog.Error.WriteLine(ex.ToString());
519 }
520 }
521 }
522 if (WindowHandles.Count == 0)
523 {
524 gLog.Error.WriteLine("Failed to get Window Handle for Process: {0} (id=0x{1:x8})", Consts.ProcessExecutable);
525 return;
526 }
527 else
528 {
529 // DXTViewer only needs the mainwindowhandle
530 IntPtr handle = IntPtr.Zero;
531 if (WindowHandles.Count > 1)
532 {
533 gLog.Warn.WriteLine("Found more than one window handle: count={0}", WindowHandles.Count);
534 throw new InvalidOperationException(string.Format("Found more than one window handle: count={0}", WindowHandles.Count));
535 }
536 else if (WindowHandles.Count == 0)
537 {
538 gLog.Warn.WriteLine("Found no window handles: count={0}", WindowHandles.Count);
539 throw new InvalidOperationException(string.Format("Found no window handles: count={0}", WindowHandles.Count));
540 }
541 else
542 {
543 handle = WindowHandles.First();
544 }
545 if (handle == IntPtr.Zero)
546 {
547 gLog.Warn.WriteLine("Found Window Handle but it was IntPtr.Zero");
548 throw new InvalidOperationException("Found Window Handle but it was IntPtr.Zero");
549 }
550 int length = GetWindowTextLength(handle);
551 StringBuilder windowTitle = new StringBuilder(length + 1);
552 GetWindowText(handle, windowTitle, windowTitle.Capacity);
553 gLog.Debug.WriteLine("Windowhandle: 0x{0:x8} ... Title: '{1}'", handle, windowTitle.ToString());
554
555 var dialog_handle = OpenFileDialog(handle);
556
557 if (dialog_handle == IntPtr.Zero)
558 {
559 gLog.Error.WriteLine("Unable to find the DXTViewer's Open File Dialog...");
560 throw new InvalidOperationException("Unable to find the DXTViewer's Open File Dialog...");
561 }
562 else
563 {
564 gLog.Debug.WriteLine("Found DXTViewer's OpenFileDialog. Handle=0x{0:x8}", dialog_handle);
565 OpenFile(handle, dialog_handle, InitParams.TargetImage);
566 }
567 #region old-code child windows
568 //IntPtr btnOKHandle = IntPtr.Zero;
569 //foreach (IntPtr WindowHandle in WindowHandles)
570 //{
571 // windowHandles = new ArrayList();
572 // if (!EnumChildWindows(WindowHandle, callBackPtr, windowHandles))
573 // {
574 // gLog.Error.WriteLine("Failed to enumerate child windows...MainWindowHandle=0x{0:x8}", WindowHandle.ToInt32());
575 // return;
576 // }
577 // else
578 // {
579 // gLog.Debug.WriteLine("Found: {0} child window handles for MainWindowHandle=0x{1:x8}", windowHandles.Count, WindowHandle.ToInt32());
580 // }
581 // var handles = windowHandles.Cast<IntPtr>().ToList();
582 // foreach (var handle in handles)
583 // {
584 // int length = GetWindowTextLength(handle);
585 // StringBuilder windowTitle = new StringBuilder(length + 1);
586 // GetWindowText(handle, windowTitle, windowTitle.Capacity);
587 // if (windowTitle.ToString().ToLower() == "ok")
588 // {
589 // btnOKHandle = handle;
590 // break;
591 // }
592 // }
593 #endregion
594
595 #region old-code controls
596 // var listbox_handle = handles.Last();
597 // IntPtr pCount = SendMessage(listbox_handle, (uint)LB.LB_GETCOUNT, 0, 0);
598 // int count = pCount.ToInt32();
599 // IntPtr result = IntPtr.Zero;
600 // gLog.Debug.WriteLine("DXTViewer::total available plugins={0}", count);
601 // List<TextIndex> items = new List<TextIndex>();
602 // //for (int i = 0; i < count; i++)
603 // //{
604 // // result = SendMessage(listbox_handle, (uint)LB.LB_GETITEMDATA, i, 0);
605 // // if (result.ToInt32() != 0)
606 // // {
607 // // // if the item is checked, uncheck it
608 // // gLog.Debug.WriteLine("DXTViewer::toggleing plugin selection at index={0}", i);
609 // // result = SendMessage(listbox_handle, (uint)LB.LB_SETITEMDATA, i, 0);
610 // // RefreshWindow(listbox_handle);
611 // // }
612 // //}
613 // for (int i = 0; i < count; i++)
614 // {
615 // StringBuilder sb = new StringBuilder(255);
616 // result = SendMessage(listbox_handle, (uint)LB.LB_GETTEXT, (IntPtr)i, sb);
617 // if (sb.ToString().Length != result.ToInt32())
618 // {
619 // gLog.Error.WriteLine("Unable to read all item text at Index: {0} (text='{1}')", i, sb.ToString());
620 // }
621 // foreach (var plugin in InitParams.TargetImage)
622 // {
623 // if (sb.ToString().ToLower() == plugin.ToLower())
624 // {
625 // items.Add(new TextIndex(i, sb.ToString()));
626 // break;
627 // }
628 // }
629 // result = SendMessage(listbox_handle, (uint)LB.LB_GETITEMDATA, i, 0);
630 // if (result.ToInt32() != 0)
631 // {
632 // // if the item is checked, uncheck it
633 // gLog.Debug.WriteLine("DXTViewer::toggleing plugin selection at index={0} ({1})", i, sb.ToString());
634 // result = SendMessage(listbox_handle, (uint)LB.LB_SETITEMDATA, i, 0);
635 // RefreshWindow(listbox_handle);
636 // }
637 // }
638 // items.TrimExcess();
639 // gLog.Debug.WriteLine("DXTViewer::total found plugins: {0} expected to find: {1}", items.Count, InitParams.TargetPlugins.Count);
640 // if (items.Count == 0 && InitParams.TargetPlugins.Count > 0)
641 // {
642 // MessageBox.Show("Could not find the requested plugin(s)...it is possible that the plugin is not in the Skyrim Data directory, as this is were DXTViewer expects them to be....", "One or more plugins not found", MessageBoxButtons.OK, MessageBoxIcon.Warning);
643 // }
644 // foreach (var item in items)
645 // {
646 // int index = item.Index;
647 // string text = item.Text;
648 // StringBuilder sb = new StringBuilder(text);
649 // gLog.Debug.WriteLine("DXTViewer::selecting plugin: index={0} ({1})", index, text);
650 // result = SendMessage(listbox_handle, (uint)LB.LB_SELECTSTRING, (IntPtr)(index - 1), sb);
651 // gLog.Debug.WriteLine("DXTViewer::activating plugin: index={0} ({1})", index, text);
652 // PostMessage(listbox_handle, WM_KEYDOWN, VkKeyScan(' '), 0);
653 // RefreshWindow(listbox_handle);
654 // Thread.Sleep(250);
655 // }
656 // if (InitParams.TargetPlugins.Count > 0 && items.Count > 0)
657 // {
658 // gLog.Debug.WriteLine("DXTViewer::sending selected plugins to main window");
659 // Thread.Sleep(500);
660 // PostMessage(btnOKHandle, WM_KEYDOWN, VkKeyScan('\n'), 0);
661 // }
662 // else
663 // {
664 // gLog.Warn.WriteLine("No plugins have been selected for editing...leaving the selection dialog open");
665 // }
666 // }
667 #endregion
668 }
669
670 }
671
672 private static void SendKey(IntPtr handle, string keys)
673 {
674 SetForegroundWindow(handle);
675 SendKeys.SendWait(keys);
676 }
677 private static IntPtr OpenFileDialog(IntPtr handle)
678 {
679 SendKey(handle, "%F");
680 SendKey(handle, "{ENTER}");
681 // get openfiledialog handle
682 var openfiledialog_handle = IntPtr.Zero;
683 var windowHandles = new ArrayList();
684 EnumedWindow callBackPtr = GetWindowHandle;
685 if (!EnumWindows(callBackPtr, windowHandles))
686 {
687 gLog.Error.WriteLine("Failed to enumerate windows...");
688 }
689 else
690 {
691 foreach (IntPtr windowhandle in windowHandles)
692 {
693 try
694 {
695 uint pid = 0;
696 GetWindowThreadProcessId(windowhandle, out pid);
697
698 int length = GetWindowTextLength(windowhandle);
699 StringBuilder windowTitle = new StringBuilder(length + 1);
700 GetWindowText(windowhandle, windowTitle, windowTitle.Capacity);
701 GetWindowThreadProcessId(windowhandle, out pid);
702 if (windowTitle.ToString() == Consts.dxtviewer_openfiledialog_title && pid == Instance.Id)
703 {
704 openfiledialog_handle = windowhandle;
705 gLog.Debug.WriteLine("Process: {0} (id=0x{1:x8} windowhandle=0x{2:x8}) title='{3}'", Consts.ProcessExecutable, pid, windowhandle.ToInt32(), windowTitle);
706 //break;
707 }
708 }
709 catch (Exception ex)
710 {
711 gLog.Error.WriteLine(ex.ToString());
712 }
713 }
714 }
715 return openfiledialog_handle;
716 }
717 private static void OpenFile(IntPtr MainHandle, IntPtr dialog_handle, string file)
718 {
719 // get handle to filename TextBox control
720 const int filename_index = 0x17;
721 IntPtr txtFilename_handle = IntPtr.Zero;
722
723 var windowHandles = new ArrayList();
724 EnumedWindow callBackPtr = GetWindowHandle;
725 if (!EnumChildWindows(dialog_handle, callBackPtr, windowHandles))
726 {
727 gLog.Error.WriteLine("Failed to enumerate child windows...MainWindowHandle=0x{0:x8}", dialog_handle.ToInt32());
728 return;
729 }
730 else
731 {
732 gLog.Debug.WriteLine("Found: {0} child window handles for MainWindowHandle=0x{1:x8}", windowHandles.Count, dialog_handle.ToInt32());
733 }
734 var handles = windowHandles.Cast<IntPtr>().ToList();
735 txtFilename_handle = handles[filename_index];
736
737 //// set the filename
738 //foreach (var ch in file.ToCharArray())
739 //{
740 // SendKey(txtFilename_handle, ch.ToString());
741 // //Thread.Sleep(100);
742 //}
743 SendKey(txtFilename_handle, file);
744 Thread.Sleep(100);
745 //Thread.Sleep(100);
746 // send enter to dialog handle
747 SendKey(dialog_handle, "{ENTER}");
748 //Thread.Sleep(100);
749 }
750 #endregion
751 #region Exceptions
752 internal class Exceptions
753 {
754 #region ProcessInstanceNotFoundException
755 internal class ProcessInstanceNotFoundException : Exception
756 {
757 static private string InternalMessage
758 {
759 get { return string.Format("Unable to find a running instance of: {0}", DXTViewer.Consts.ProcessExecutable); }
760 }
761 static private string InternalMessageCaption
762 {
763 get { return string.Format("{0} instance not found", DXTViewer.Consts.ProcessExecutable); }
764 }
765 public ProcessInstanceNotFoundException() : this(null) { }
766 public ProcessInstanceNotFoundException(Exception innerException) : this(false, innerException) { }
767 public ProcessInstanceNotFoundException(bool DisplayMessage) : this(DisplayMessage, null) { }
768 public ProcessInstanceNotFoundException(bool DisplayMessage, Exception innerException)
769 : base(InternalMessage, innerException)
770 {
771 gLog.Error.WriteLine(this.ToString());
772 if (DisplayMessage)
773 {
774 MessageBox.Show(InternalMessage, InternalMessageCaption, MessageBoxButtons.OK, MessageBoxIcon.Error);
775 }
776 }
777 }
778 #endregion
779
780 #region ModuleNotFoundException
781 internal class ModuleNotFoundException : Exception
782 {
783 static private string InternalMessage
784 {
785 get { return string.Format("Unable to find module: {0}", Consts.ProcessExecutable); }
786 }
787 static private string InternalMessageCaption
788 {
789 get { return string.Format("{0} module not found", Consts.ProcessExecutable); }
790 }
791 public ModuleNotFoundException() : this(null) { }
792 public ModuleNotFoundException(Exception innerException) : this(false, innerException) { }
793 public ModuleNotFoundException(bool DisplayMessage) : this(DisplayMessage, null) { }
794 public ModuleNotFoundException(bool DisplayMessage, Exception innerException)
795 : base(InternalMessage, innerException)
796 {
797 gLog.Error.WriteLine(this.ToString());
798 if (DisplayMessage)
799 {
800 MessageBox.Show(InternalMessage, InternalMessageCaption, MessageBoxButtons.OK, MessageBoxIcon.Error);
801 }
802 }
803 }
804 #endregion
805
806 #region ConfigNotFoundException
807 internal class ConfigNotFoundException : Exception
808 {
809 static private string InternalMessage
810 {
811 get { return string.Format("Unable to find config: {0}", Consts.ConfigName); }
812 }
813 static private string InternalMessageCaption
814 {
815 get { return string.Format("{0} config not found", Consts.ConfigName); }
816 }
817 public ConfigNotFoundException() : this(null) { }
818 public ConfigNotFoundException(Exception innerException) : this(false, innerException) { }
819 public ConfigNotFoundException(bool DisplayMessage) : this(DisplayMessage, null) { }
820 public ConfigNotFoundException(bool DisplayMessage, Exception innerException)
821 : base(InternalMessage, innerException)
822 {
823 gLog.Error.WriteLine(this.ToString());
824 if (DisplayMessage)
825 {
826 MessageBox.Show(InternalMessage, InternalMessageCaption, MessageBoxButtons.OK, MessageBoxIcon.Error);
827 }
828 }
829 }
830 #endregion
831
832 #region ConfigParameterNotFoundException
833 internal class ConfigParameterNotFoundException : Exception
834 {
835 static private string InternalMessage(string parameterName)
836 {
837 return string.Format("Unable to find config parameter: {0}", parameterName);
838 }
839 static private string InternalMessageCaption(string parameterName)
840 {
841 return string.Format("{0} parameter not found", parameterName);
842 }
843 public ConfigParameterNotFoundException(string parameterName) : this(parameterName, null) { }
844 public ConfigParameterNotFoundException(string parameterName, Exception innerException) : this(false, parameterName, innerException) { }
845 public ConfigParameterNotFoundException(bool DisplayMessage, string parameterName) : this(DisplayMessage, parameterName, null) { }
846 public ConfigParameterNotFoundException(bool DisplayMessage, string parameterName, Exception innerException)
847 : base(InternalMessage(parameterName), innerException)
848 {
849 gLog.Error.WriteLine(this.ToString());
850 if (DisplayMessage)
851 {
852 MessageBox.Show(InternalMessage(parameterName), InternalMessageCaption(parameterName), MessageBoxButtons.OK, MessageBoxIcon.Error);
853 }
854 }
855 }
856 #endregion
857
858 #region UnableToStartProcessException
859 internal class UnableToStartProcessException : Exception
860 {
861 static private string InternalMessage
862 {
863 get { return string.Format("Unable to start process: {0}", Consts.ProcessExecutable); }
864 }
865 static private string InternalMessageCaption
866 {
867 get { return string.Format("{0} process not started", Consts.ProcessExecutable); }
868 }
869 public UnableToStartProcessException() : this(null) { }
870 public UnableToStartProcessException(Exception innerException) : this(false, innerException) { }
871 public UnableToStartProcessException(bool DisplayMessage) : this(DisplayMessage, null) { }
872 public UnableToStartProcessException(bool DisplayMessage, Exception innerException)
873 : base(InternalMessage, innerException)
874 {
875 gLog.Error.WriteLine(this.ToString());
876 if (DisplayMessage)
877 {
878 MessageBox.Show(InternalMessage, InternalMessageCaption, MessageBoxButtons.OK, MessageBoxIcon.Error);
879 }
880 }
881 }
882 #endregion
883
884 #region PluginNotFoundException
885 internal class ImageNotFoundException : Exception
886 {
887 static private string InternalMessage(string pluginfile)
888 {
889 return string.Format("Unable to find plugin: {0}", pluginfile);
890 }
891 static private string InternalMessageCaption(string pluginfile)
892 {
893 return string.Format("{0} plugin not found", pluginfile);
894 }
895 public ImageNotFoundException(string pluginfile) : this(pluginfile, null) { }
896 public ImageNotFoundException(string pluginfile, Exception innerException) : this(false, pluginfile, innerException) { }
897 public ImageNotFoundException(bool DisplayMessage, string pluginfile) : this(DisplayMessage, pluginfile, null) { }
898 public ImageNotFoundException(bool DisplayMessage, string pluginfile, Exception innerException)
899 : base(InternalMessage(pluginfile), innerException)
900 {
901 gLog.Error.WriteLine(this.ToString());
902 if (DisplayMessage)
903 {
904 MessageBox.Show(InternalMessage(pluginfile), InternalMessageCaption(pluginfile), MessageBoxButtons.OK, MessageBoxIcon.Error);
905 }
906 }
907 }
908 #endregion
909
910 #endregion
911 }
912 }
913
914 }

  ViewVC Help
Powered by ViewVC 1.1.22