OSDN Git Service

コメントアウトされた不要なコードを削除
[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 #nullable enable
29
30 using System;
31 using System.ComponentModel;
32 using System.Diagnostics;
33 using System.Linq;
34 using System.Net;
35 using System.Runtime.InteropServices;
36 using System.Threading;
37 using System.Windows.Forms;
38 using System.Text;
39 using OpenTween.Connection;
40
41 namespace OpenTween
42 {
43     internal static class NativeMethods
44     {
45         // 指定されたウィンドウへ、指定されたメッセージを送信します
46         [DllImport("user32.dll")]
47         private extern static IntPtr SendMessage(
48             IntPtr hwnd,
49             SendMessageType wMsg,
50             IntPtr wParam,
51             IntPtr lParam);
52
53         [DllImport("user32.dll")]
54         private extern static IntPtr SendMessage(
55             IntPtr hwnd,
56             SendMessageType wMsg,
57             IntPtr wParam,
58             ref LVITEM lParam);
59
60         // SendMessageで送信するメッセージ
61         private enum SendMessageType : uint
62         {
63             WM_SETREDRAW = 0x000B,               //再描画を許可するかを設定
64             WM_USER = 0x400,                     //ユーザー定義メッセージ
65
66             TCM_FIRST = 0x1300,                  //タブコントロールメッセージ
67             TCM_SETMINTABWIDTH = TCM_FIRST + 49, //タブアイテムの最小幅を設定
68
69             LVM_FIRST = 0x1000,                    //リストビューメッセージ
70             LVM_SETITEMSTATE = LVM_FIRST + 43,     //アイテムの状態を設定
71             LVM_GETSELECTIONMARK = LVM_FIRST + 66, //複数選択時の起点になるアイテムの位置を取得
72             LVM_SETSELECTIONMARK = LVM_FIRST + 67, //複数選択時の起点になるアイテムを設定
73         }
74
75         /// <summary>
76         /// コントロールの再描画を許可するかを設定します
77         /// </summary>
78         /// <param name="control">対象となるコントロール</param>
79         /// <param name="redraw">再描画を許可する場合は true、抑制する場合は false</param>
80         /// <returns>このメッセージを処理する場合、アプリケーションは 0 を返します</returns>
81         public static int SetRedrawState(Control control, bool redraw)
82         {
83             var state = redraw ? new IntPtr(1) : IntPtr.Zero;
84             return (int)SendMessage(control.Handle, SendMessageType.WM_SETREDRAW, state, IntPtr.Zero);
85         }
86
87         /// <summary>
88         /// タブコントロールのアイテムの最小幅を設定します
89         /// </summary>
90         /// <param name="tabControl">対象となるタブコントロール</param>
91         /// <param name="width">アイテムの最小幅。-1 を指定するとデフォルトの幅が使用されます</param>
92         /// <returns>設定前の最小幅</returns>
93         public static int SetMinTabWidth(TabControl tabControl, int width)
94             => (int)SendMessage(tabControl.Handle, SendMessageType.TCM_SETMINTABWIDTH, IntPtr.Zero, (IntPtr)width);
95
96         // 参照: LVITEM structure (Windows)
97         // http://msdn.microsoft.com/en-us/library/windows/desktop/bb774760%28v=vs.85%29.aspx
98         [StructLayout(LayoutKind.Sequential)]
99         [BestFitMapping(false, ThrowOnUnmappableChar = true)]
100         private struct LVITEM
101         {
102             public uint mask;
103             public int iItem;
104             public int iSubItem;
105             public LVIS state;
106             public LVIS stateMask;
107             public string pszText;
108             public int cchTextMax;
109             public int iImage;
110             public IntPtr lParam;
111             public int iIndent;
112             public int iGroupId;
113             public uint cColumns;
114             public uint puColumns;
115             public int piColFmt;
116             public int iGroup;
117         }
118
119         // 参照: List-View Item States (Windows)
120         // http://msdn.microsoft.com/en-us/library/windows/desktop/bb774733%28v=vs.85%29.aspx
121         [Flags]
122         private enum LVIS : uint
123         {
124             SELECTED = 0x02,
125         }
126
127         /// <summary>
128         /// ListView のアイテムを選択された状態にします
129         /// </summary>
130         /// <param name="listView">対象となる ListView</param>
131         /// <param name="index">選択するアイテムのインデックス</param>
132         /// <returns>成功した場合は true、それ以外の場合は false</returns>
133         public static bool SelectItem(ListView listView, int index)
134         {
135             // LVM_SETITEMSTATE では stateMask, state 以外のメンバーは無視される
136             var lvitem = new LVITEM
137             {
138                 stateMask = LVIS.SELECTED,
139                 state = LVIS.SELECTED,
140             };
141
142             var ret = (int)SendMessage(listView.Handle, SendMessageType.LVM_SETITEMSTATE, (IntPtr)index, ref lvitem);
143             return ret != 0;
144         }
145
146         /// <summary>
147         /// ListView の全アイテムを選択された状態にします
148         /// </summary>
149         /// <param name="listView">対象となる ListView</param>
150         /// <returns>成功した場合は true、それ以外の場合は false</returns>
151         public static bool SelectAllItems(ListView listView)
152             => SelectItem(listView, -1 /* all items */);
153
154         #region "画面ブリンク用"
155         public static bool FlashMyWindow(IntPtr hwnd, 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             DIRECT = 1, // Direct
325             PROXY = 3, // Custom
326         }
327
328         private static void RefreshProxySettings(string? strProxy)
329         {
330             InternetProxyInfo ipi;
331
332             // Filling in structure
333             if (!string.IsNullOrEmpty(strProxy))
334             {
335                 ipi = new InternetProxyInfo
336                 {
337                     dwAccessType = InternetOpenType.PROXY,
338                     proxy = strProxy,
339                     proxyBypass = "local",
340                 };
341             }
342             else if (strProxy == null)
343             {
344                 //IE Default
345                 var p = WebRequest.GetSystemWebProxy();
346                 if (p.IsBypassed(new Uri("http://www.google.com/")))
347                 {
348                     ipi = new InternetProxyInfo
349                     {
350                         dwAccessType = InternetOpenType.DIRECT,
351                         proxy = null,
352                         proxyBypass = null,
353                     };
354                 }
355                 else
356                 {
357                     ipi = new InternetProxyInfo
358                     {
359                         dwAccessType = InternetOpenType.PROXY,
360                         proxy = p.GetProxy(new Uri("http://www.google.com/")).Authority,
361                         proxyBypass = "local",
362                     };
363                 }
364             }
365             else
366             {
367                 ipi = new InternetProxyInfo
368                 {
369                     dwAccessType = InternetOpenType.DIRECT,
370                     proxy = null,
371                     proxyBypass = null,
372                 };
373             }
374
375             if (!InternetSetOption(IntPtr.Zero, InternetOption.PROXY, ref ipi, Marshal.SizeOf(ipi)))
376                 throw new Win32Exception();
377         }
378
379         public static void SetProxy(ProxyType pType, string host, int port)
380         {
381             var proxy = pType switch
382             {
383                 ProxyType.IE => null,
384                 ProxyType.None => "",
385                 ProxyType.Specified => host + (port > 0 ? ":" + port : ""),
386                 _ => null,
387             };
388             RefreshProxySettings(proxy);
389         }
390 #endregion
391
392         [StructLayout(LayoutKind.Sequential)]
393         private struct SCROLLINFO
394         {
395             public int cbSize;
396             public ScrollInfoMask fMask;
397             public int nMin;
398             public int nMax;
399             public int nPage;
400             public int nPos;
401             public int nTrackPos;
402         }
403
404         public enum ScrollBarDirection
405         {
406             SB_HORZ = 0,
407             SB_VERT = 1,
408             SB_CTL = 2,
409             SB_BOTH = 3,
410         }
411
412         private enum ScrollInfoMask
413         {
414             SIF_RANGE = 0x1,
415             SIF_PAGE = 0x2,
416             SIF_POS = 0x4,
417             SIF_DISABLENOSCROLL = 0x8,
418             SIF_TRACKPOS = 0x10,
419             SIF_ALL = (SIF_RANGE | SIF_PAGE | SIF_POS | SIF_TRACKPOS),
420         }
421
422         [DllImport("user32.dll")]
423         private static extern int GetScrollInfo(IntPtr hWnd, ScrollBarDirection fnBar, ref SCROLLINFO lpsi);
424
425         public static int GetScrollPosition(Control control, ScrollBarDirection direction)
426         {
427             var si = new SCROLLINFO
428             {
429                 cbSize = Marshal.SizeOf<SCROLLINFO>(),
430                 fMask = ScrollInfoMask.SIF_POS,
431             };
432
433             if (NativeMethods.GetScrollInfo(control.Handle, direction, ref si) == 0)
434                 throw new Win32Exception();
435
436             return si.nPos;
437         }
438
439         #region "ウィンドウの検索"
440
441         [DllImport("user32.dll")]
442         private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint procId);
443         
444         [return: MarshalAs(UnmanagedType.Bool)]
445         private delegate bool EnumWindowCallback(IntPtr hWnd, int lParam);
446
447         [DllImport("user32")]
448         [return: MarshalAs(UnmanagedType.Bool)]
449         private static extern bool EnumWindows(EnumWindowCallback lpEnumFunc, IntPtr lParam);
450
451         [DllImport("user32.dll", CharSet = CharSet.Unicode)]
452         private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
453
454         [DllImport("user32.dll", CharSet = CharSet.Unicode)]
455         private static extern int GetWindowTextLength(IntPtr hWnd);
456
457         /// <summary>
458         /// 指定したPIDとタイトルを持つウィンドウのウィンドウハンドルを取得します
459         /// </summary>
460         /// <param name="pid">対象ウィンドウのPID</param>
461         /// <param name="searchWindowTitle">対象ウィンドウのタイトル</param>
462         /// <returns>ウィンドウハンドル。検索に失敗した場合は<see cref="IntPtr.Zero"/></returns>
463         public static IntPtr GetWindowHandle(uint pid, string searchWindowTitle)
464         {
465             var foundHwnd = IntPtr.Zero;
466
467             EnumWindows((hWnd, lParam) =>
468             {
469                 GetWindowThreadProcessId(hWnd, out var procId);
470
471                 if (procId == pid)
472                 {
473                     var windowTitleLen = GetWindowTextLength(hWnd);
474
475                     if (windowTitleLen > 0)
476                     {
477                         var windowTitle = new StringBuilder(windowTitleLen + 1);
478                         GetWindowText(hWnd, windowTitle, windowTitle.Capacity);
479
480                         if (windowTitle.ToString().Contains(searchWindowTitle))
481                         {
482                             foundHwnd = hWnd;
483                             return false;
484                         }
485                     }
486                 }
487
488                 return true;
489             }, IntPtr.Zero);
490
491             return foundHwnd;
492         }
493
494         #endregion
495
496         #region "ウィンドウのアクティブ化"
497
498         private enum ShowWindowCommands : int
499         {
500             /// <summary>最小化・最大化されたウィンドウを元に戻して表示</summary>
501             SW_RESTORE = 9,
502         }
503
504         [DllImport("user32.dll")]
505         [return: MarshalAs(UnmanagedType.Bool)]
506         private static extern bool ShowWindow(IntPtr hWnd, ShowWindowCommands nCmdShow);
507
508         [DllImport("user32.dll")]
509         [return: MarshalAs(UnmanagedType.Bool)]
510         private static extern bool SetForegroundWindow(IntPtr hWnd);
511
512         /// <summary>
513         /// 指定したウィンドウをアクティブにします
514         /// </summary>
515         /// <param name="hWnd">アクティブにするウィンドウのウィンドウハンドル</param>
516         public static void SetActiveWindow(IntPtr hWnd)
517         {
518             ShowWindow(hWnd, ShowWindowCommands.SW_RESTORE);
519             SetForegroundWindow(hWnd);
520         }
521
522         #endregion
523     }
524 }