OSDN Git Service

シンプルな型名を使用する (IDE0049)
[opentween/open-tween.git] / OpenTween / NativeMethods.cs
1 // OpenTween - Client of Twitter
2 // Copyright (c) 2007-2011 kiri_feather (@kiri_feather) <kiri.feather@gmail.com>
3 //           (c) 2008-2011 Moz (@syo68k)
4 //           (c) 2008-2011 takeshik (@takeshik) <http://www.takeshik.org/>
5 //           (c) 2010-2011 anis774 (@anis774) <http://d.hatena.ne.jp/anis774/>
6 //           (c) 2010-2011 fantasticswallow (@f_swallow) <http://twitter.com/f_swallow>
7 //           (c) 2011      Egtra (@egtra) <http://dev.activebasic.com/egtra/>
8 //           (c) 2014      kim_upsilon (@kim_upsilon) <https://upsilo.net/~upsilon/>
9 // All rights reserved.
10 // 
11 // This file is part of OpenTween.
12 // 
13 // This program is free software; you can redistribute it and/or modify it
14 // under the terms of the GNU General public License as published by the Free
15 // Software Foundation; either version 3 of the License, or (at your option)
16 // any later version.
17 // 
18 // This program is distributed in the hope that it will be useful, but
19 // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
20 // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General public License
21 // for more details. 
22 // 
23 // You should have received a copy of the GNU General public License along
24 // with this program. if not, see <http://www.gnu.org/licenses/>, or write to
25 // the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
26 // Boston, MA 02110-1301, USA.
27
28 using System;
29 using System.ComponentModel;
30 using System.Diagnostics;
31 using System.Linq;
32 using System.Net;
33 using System.Runtime.InteropServices;
34 using System.Threading;
35 using System.Windows.Forms;
36 using System.Text;
37 using OpenTween.Connection;
38
39 namespace OpenTween
40 {
41     internal static class NativeMethods
42     {
43         // 指定されたウィンドウへ、指定されたメッセージを送信します
44         [DllImport("user32.dll")]
45         private extern static IntPtr SendMessage(
46             IntPtr hwnd,
47             SendMessageType wMsg,
48             IntPtr wParam,
49             IntPtr lParam);
50
51         [DllImport("user32.dll")]
52         private extern static IntPtr SendMessage(
53             IntPtr hwnd,
54             SendMessageType wMsg,
55             IntPtr wParam,
56             ref LVITEM lParam);
57
58         // SendMessageで送信するメッセージ
59         private enum SendMessageType : uint
60         {
61             WM_SETREDRAW = 0x000B,               //再描画を許可するかを設定
62             WM_USER = 0x400,                     //ユーザー定義メッセージ
63
64             TCM_FIRST = 0x1300,                  //タブコントロールメッセージ
65             TCM_SETMINTABWIDTH = TCM_FIRST + 49, //タブアイテムの最小幅を設定
66
67             LVM_FIRST = 0x1000,                    //リストビューメッセージ
68             LVM_SETITEMSTATE = LVM_FIRST + 43,     //アイテムの状態を設定
69             LVM_GETSELECTIONMARK = LVM_FIRST + 66, //複数選択時の起点になるアイテムの位置を取得
70             LVM_SETSELECTIONMARK = LVM_FIRST + 67, //複数選択時の起点になるアイテムを設定
71         }
72
73         /// <summary>
74         /// コントロールの再描画を許可するかを設定します
75         /// </summary>
76         /// <param name="control">対象となるコントロール</param>
77         /// <param name="redraw">再描画を許可する場合は true、抑制する場合は false</param>
78         /// <returns>このメッセージを処理する場合、アプリケーションは 0 を返します</returns>
79         public static int SetRedrawState(Control control, bool redraw)
80         {
81             var state = redraw ? new IntPtr(1) : IntPtr.Zero;
82             return (int)SendMessage(control.Handle, SendMessageType.WM_SETREDRAW, state, IntPtr.Zero);
83         }
84
85         /// <summary>
86         /// タブコントロールのアイテムの最小幅を設定します
87         /// </summary>
88         /// <param name="tabControl">対象となるタブコントロール</param>
89         /// <param name="width">アイテムの最小幅。-1 を指定するとデフォルトの幅が使用されます</param>
90         /// <returns>設定前の最小幅</returns>
91         public static int SetMinTabWidth(TabControl tabControl, int width)
92             => (int)SendMessage(tabControl.Handle, SendMessageType.TCM_SETMINTABWIDTH, IntPtr.Zero, (IntPtr)width);
93
94         // 参照: LVITEM structure (Windows)
95         // http://msdn.microsoft.com/en-us/library/windows/desktop/bb774760%28v=vs.85%29.aspx
96         [StructLayout(LayoutKind.Sequential)]
97         [BestFitMapping(false, ThrowOnUnmappableChar = true)]
98         private struct LVITEM
99         {
100             public uint mask;
101             public int iItem;
102             public int iSubItem;
103             public LVIS state;
104             public LVIS stateMask;
105             public string pszText;
106             public int cchTextMax;
107             public int iImage;
108             public IntPtr lParam;
109             public int iIndent;
110             public int iGroupId;
111             public uint cColumns;
112             public uint puColumns;
113             public int piColFmt;
114             public int iGroup;
115         }
116
117         // 参照: List-View Item States (Windows)
118         // http://msdn.microsoft.com/en-us/library/windows/desktop/bb774733%28v=vs.85%29.aspx
119         [Flags]
120         private enum LVIS : uint
121         {
122             SELECTED = 0x02,
123         }
124
125         /// <summary>
126         /// ListView のアイテムを選択された状態にします
127         /// </summary>
128         /// <param name="listView">対象となる ListView</param>
129         /// <param name="index">選択するアイテムのインデックス</param>
130         /// <returns>成功した場合は true、それ以外の場合は false</returns>
131         public static bool SelectItem(ListView listView, int index)
132         {
133             // LVM_SETITEMSTATE では stateMask, state 以外のメンバーは無視される
134             var lvitem = new LVITEM
135             {
136                 stateMask = LVIS.SELECTED,
137                 state = LVIS.SELECTED,
138             };
139
140             var ret = (int)SendMessage(listView.Handle, SendMessageType.LVM_SETITEMSTATE, (IntPtr)index, ref lvitem);
141             return ret != 0;
142         }
143
144         /// <summary>
145         /// ListView の全アイテムを選択された状態にします
146         /// </summary>
147         /// <param name="listView">対象となる ListView</param>
148         /// <returns>成功した場合は true、それ以外の場合は false</returns>
149         public static bool SelectAllItems(ListView listView)
150             => SelectItem(listView, -1 /* all items */);
151
152         #region "画面ブリンク用"
153         public static bool FlashMyWindow(IntPtr hwnd,
154             FlashSpecification flashType,
155             int flashCount)
156         {
157             var fInfo = new FLASHWINFO();
158             fInfo.cbSize = Convert.ToInt32(Marshal.SizeOf(fInfo));
159             fInfo.hwnd = hwnd;
160             fInfo.dwFlags = (int)FlashSpecification.FlashAll;
161             fInfo.uCount = flashCount;
162             fInfo.dwTimeout = 0;
163
164             return FlashWindowEx(ref fInfo);
165         }
166
167         public enum FlashSpecification : uint
168         {
169             FlashStop = FLASHW_STOP,
170             FlashCaption = FLASHW_CAPTION,
171             FlashTray = FLASHW_TRAY,
172             FlashAll = FLASHW_ALL,
173             FlashTimer = FLASHW_TIMER,
174             FlashTimerNoForeground = FLASHW_TIMERNOFG,
175         }
176         /// http://www.atmarkit.co.jp/fdotnet/dotnettips/723flashwindow/flashwindow.html
177         [DllImport("user32.dll")]
178         [return: MarshalAs(UnmanagedType.Bool)]
179         private static extern bool FlashWindowEx(
180             ref FLASHWINFO FWInfo);
181
182
183         private struct FLASHWINFO
184         {
185             public int cbSize;    // FLASHWINFO構造体のサイズ
186             public IntPtr hwnd;     // 点滅対象のウィンドウ・ハンドル
187             public int dwFlags;   // 以下の「FLASHW_XXX」のいずれか
188             public int uCount;    // 点滅する回数
189             public int dwTimeout; // 点滅する間隔(ミリ秒単位)
190         }
191
192         // 点滅を止める
193         private const int FLASHW_STOP = 0;
194         // タイトルバーを点滅させる
195         private const int FLASHW_CAPTION = 0x1;
196         // タスクバー・ボタンを点滅させる
197         private const int FLASHW_TRAY = 0x2;
198         // タスクバー・ボタンとタイトルバーを点滅させる
199         private const int FLASHW_ALL = 0x3;
200         // FLASHW_STOPが指定されるまでずっと点滅させる
201         private const int FLASHW_TIMER = 0x4;
202         // ウィンドウが最前面に来るまでずっと点滅させる
203         private const int FLASHW_TIMERNOFG = 0xC;
204         #endregion
205
206         [DllImport("user32.dll")]
207         [return: MarshalAs(UnmanagedType.Bool)]
208         public static extern bool ValidateRect(
209             IntPtr hwnd,
210             IntPtr rect);
211
212         #region "selection mark"
213         // 複数選択時の起点になるアイテム (selection mark) の位置を取得する
214         public static int ListView_GetSelectionMark(IntPtr hwndLV)
215             => SendMessage(hwndLV, SendMessageType.LVM_GETSELECTIONMARK, IntPtr.Zero, IntPtr.Zero).ToInt32();
216
217         // 複数選択時の起点になるアイテム (selection mark) を設定する
218         public static void ListView_SetSelectionMark(IntPtr hwndLV, int itemIndex)
219             => SendMessage(hwndLV, SendMessageType.LVM_SETSELECTIONMARK, IntPtr.Zero, (IntPtr)itemIndex);
220         #endregion
221
222         #region "スクリーンセーバー起動中か判定"
223         [DllImport("user32", CharSet = CharSet.Auto)]
224         [return: MarshalAs(UnmanagedType.Bool)]
225         private static extern bool SystemParametersInfo(
226                     int intAction,
227                     int intParam,
228                     [MarshalAs(UnmanagedType.Bool)] ref bool bParam,
229                     int intWinIniFlag);
230         // returns non-zero value if function succeeds
231
232         //スクリーンセーバーが起動中かを取得する定数
233         private const int SPI_GETSCREENSAVERRUNNING = 0x0072;
234
235         public static bool IsScreenSaverRunning()
236         {
237             var isRunning = false;
238             SystemParametersInfo(SPI_GETSCREENSAVERRUNNING, 0, ref isRunning, 0);
239             return isRunning;
240         }
241         #endregion
242
243         #region "グローバルフック"
244         [DllImport("user32")]
245         private static extern int RegisterHotKey(IntPtr hwnd, int id,
246             int fsModifiers, int vk);
247         [DllImport("user32")]
248         private static extern int UnregisterHotKey(IntPtr hwnd, int id);
249         [DllImport("kernel32", CharSet = CharSet.Auto, BestFitMapping = false, ThrowOnUnmappableChar = true)]
250         private static extern ushort GlobalAddAtom([MarshalAs(UnmanagedType.LPTStr)] string lpString);
251         [DllImport("kernel32")]
252         private static extern ushort GlobalDeleteAtom(ushort nAtom);
253
254         private static int registerCount = 0;
255         // register a global hot key
256         public static int RegisterGlobalHotKey(int hotkeyValue, int modifiers, Form targetForm)
257         {
258             ushort hotkeyID = 0;
259             try
260             {
261                 // use the GlobalAddAtom API to get a unique ID (as suggested by MSDN docs)
262                 registerCount++;
263                 var atomName = Thread.CurrentThread.ManagedThreadId.ToString("X8") + targetForm.Name + registerCount;
264                 hotkeyID = GlobalAddAtom(atomName);
265                 if (hotkeyID == 0)
266                 {
267                     throw new Win32Exception();
268                 }
269
270                 // register the hotkey, throw if any error
271                 if (RegisterHotKey(targetForm.Handle, hotkeyID, modifiers, hotkeyValue) == 0)
272                 {
273                     throw new Win32Exception();
274                 }
275                 return hotkeyID;
276             }
277             catch (Exception)
278             {
279                 // clean up if hotkey registration failed
280                 UnregisterGlobalHotKey(hotkeyID, targetForm);
281                 return 0;
282             }
283         }
284
285         // unregister a global hotkey
286         public static void UnregisterGlobalHotKey(ushort hotkeyID, Form targetForm)
287         {
288             if (hotkeyID != 0)
289             {
290                 UnregisterHotKey(targetForm.Handle, hotkeyID);
291                 // clean up the atom list
292                 GlobalDeleteAtom(hotkeyID);
293             }
294         }
295         #endregion
296
297         #region "プロセスのProxy設定"
298
299         [DllImport("wininet.dll", SetLastError = true)]
300         [return: MarshalAs(UnmanagedType.Bool)]
301         private static extern bool InternetSetOption(IntPtr hInternet,
302             InternetOption dwOption,
303             [In] ref InternetProxyInfo lpBuffer,
304             int lpdwBufferLength);
305
306         private enum InternetOption
307         {
308             PROXY = 38,
309             PROXY_USERNAME = 43,
310             PROXY_PASSWORD = 44,
311         }
312
313         [StructLayout(LayoutKind.Sequential)]
314         [BestFitMapping(false, ThrowOnUnmappableChar = true)]
315         private struct InternetProxyInfo
316         {
317             public InternetOpenType dwAccessType;
318             public string proxy;
319             public string proxyBypass;
320         }
321
322         private enum InternetOpenType
323         {
324             //PRECONFIG = 0, // IE setting
325             DIRECT = 1, // Direct
326             PROXY = 3, // Custom
327         }
328
329         private static void RefreshProxySettings(string strProxy)
330         {
331             InternetProxyInfo ipi;
332
333             // Filling in structure
334             if (!string.IsNullOrEmpty(strProxy))
335             {
336                 ipi = new InternetProxyInfo
337                 {
338                     dwAccessType = InternetOpenType.PROXY,
339                     proxy = strProxy,
340                     proxyBypass = "local",
341                 };
342             }
343             else if (strProxy == null)
344             {
345                 //IE Default
346                 var p = WebRequest.GetSystemWebProxy();
347                 if (p.IsBypassed(new Uri("http://www.google.com/")))
348                 {
349                     ipi = new InternetProxyInfo
350                     {
351                         dwAccessType = InternetOpenType.DIRECT,
352                         proxy = null,
353                         proxyBypass = null,
354                     };
355                 }
356                 else
357                 {
358                     ipi = new InternetProxyInfo
359                     {
360                         dwAccessType = InternetOpenType.PROXY,
361                         proxy = p.GetProxy(new Uri("http://www.google.com/")).Authority,
362                         proxyBypass = "local",
363                     };
364                 }
365             }
366             else
367             {
368                 ipi = new InternetProxyInfo
369                 {
370                     dwAccessType = InternetOpenType.DIRECT,
371                     proxy = null,
372                     proxyBypass = null,
373                 };
374             }
375
376             if (!InternetSetOption(IntPtr.Zero, InternetOption.PROXY, ref ipi, Marshal.SizeOf(ipi)))
377                 throw new Win32Exception();
378         }
379
380         public static void SetProxy(ProxyType pType, string host, int port, string username, string password)
381         {
382             string proxy = null;
383             switch (pType)
384             {
385             case ProxyType.IE:
386                 proxy = null;
387                 break;
388             case ProxyType.None:
389                 proxy = "";
390                 break;
391             case ProxyType.Specified:
392                 proxy = host + (port > 0 ? ":" + port : "");
393                 break;
394             }
395             RefreshProxySettings(proxy);
396         }
397 #endregion
398
399         [StructLayout(LayoutKind.Sequential)]
400         private struct SCROLLINFO
401         {
402             public int cbSize;
403             public ScrollInfoMask fMask;
404             public int nMin;
405             public int nMax;
406             public int nPage;
407             public int nPos;
408             public int nTrackPos;
409         }
410
411         public enum ScrollBarDirection
412         {
413             SB_HORZ = 0,
414             SB_VERT = 1,
415             SB_CTL = 2,
416             SB_BOTH = 3,
417         }
418
419         private enum ScrollInfoMask
420         {
421             SIF_RANGE = 0x1,
422             SIF_PAGE = 0x2,
423             SIF_POS = 0x4,
424             SIF_DISABLENOSCROLL = 0x8,
425             SIF_TRACKPOS = 0x10,
426             SIF_ALL = (SIF_RANGE | SIF_PAGE | SIF_POS | SIF_TRACKPOS),
427         }
428
429         [DllImport("user32.dll")]
430         private static extern int GetScrollInfo(IntPtr hWnd, ScrollBarDirection fnBar, ref SCROLLINFO lpsi);
431
432         public static int GetScrollPosition(Control control, ScrollBarDirection direction)
433         {
434             var si = new SCROLLINFO
435             {
436                 cbSize = Marshal.SizeOf<SCROLLINFO>(),
437                 fMask = ScrollInfoMask.SIF_POS,
438             };
439
440             if (NativeMethods.GetScrollInfo(control.Handle, direction, ref si) == 0)
441                 throw new Win32Exception();
442
443             return si.nPos;
444         }
445
446         #region "ウィンドウの検索"
447
448         [DllImport("user32.dll")]
449         private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint procId);
450         
451         [return: MarshalAs(UnmanagedType.Bool)]
452         private delegate bool EnumWindowCallback(IntPtr hWnd, int lParam);
453
454         [DllImport("user32")]
455         [return: MarshalAs(UnmanagedType.Bool)]
456         private static extern bool EnumWindows(EnumWindowCallback lpEnumFunc, IntPtr lParam);
457
458         [DllImport("user32.dll", CharSet = CharSet.Unicode)]
459         private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
460
461         [DllImport("user32.dll", CharSet = CharSet.Unicode)]
462         private static extern int GetWindowTextLength(IntPtr hWnd);
463
464         /// <summary>
465         /// 指定したPIDとタイトルを持つウィンドウのウィンドウハンドルを取得します
466         /// </summary>
467         /// <param name="pid">対象ウィンドウのPID</param>
468         /// <param name="searchWindowTitle">対象ウィンドウのタイトル</param>
469         /// <returns>ウィンドウハンドル。検索に失敗した場合は<see cref="IntPtr.Zero"/></returns>
470         public static IntPtr GetWindowHandle(uint pid, string searchWindowTitle)
471         {
472             var foundHwnd = IntPtr.Zero;
473
474             EnumWindows((hWnd, lParam) =>
475             {
476                 GetWindowThreadProcessId(hWnd, out var procId);
477
478                 if (procId == pid)
479                 {
480                     var windowTitleLen = GetWindowTextLength(hWnd);
481
482                     if (windowTitleLen > 0)
483                     {
484                         var windowTitle = new StringBuilder(windowTitleLen + 1);
485                         GetWindowText(hWnd, windowTitle, windowTitle.Capacity);
486
487                         if (windowTitle.ToString().Contains(searchWindowTitle))
488                         {
489                             foundHwnd = hWnd;
490                             return false;
491                         }
492                     }
493                 }
494
495                 return true;
496             }, IntPtr.Zero);
497
498             return foundHwnd;
499         }
500
501         #endregion
502
503         #region "ウィンドウのアクティブ化"
504
505         private enum ShowWindowCommands : int
506         {
507             /// <summary>最小化・最大化されたウィンドウを元に戻して表示</summary>
508             SW_RESTORE = 9,
509         }
510
511         [DllImport("user32.dll")]
512         [return: MarshalAs(UnmanagedType.Bool)]
513         private static extern bool ShowWindow(IntPtr hWnd, ShowWindowCommands nCmdShow);
514
515         [DllImport("user32.dll")]
516         [return: MarshalAs(UnmanagedType.Bool)]
517         private static extern bool SetForegroundWindow(IntPtr hWnd);
518
519         /// <summary>
520         /// 指定したウィンドウをアクティブにします
521         /// </summary>
522         /// <param name="hWnd">アクティブにするウィンドウのウィンドウハンドル</param>
523         public static void SetActiveWindow(IntPtr hWnd)
524         {
525             ShowWindow(hWnd, ShowWindowCommands.SW_RESTORE);
526             SetForegroundWindow(hWnd);
527         }
528
529         #endregion
530     }
531 }