Eine fremde, nicht C# Anwendung davon abhalten mit Alt + F4 geschlossen zu werden. Ist es möglich?

  • C#

Es gibt 10 Antworten in diesem Thema. Der letzte Beitrag () ist von VaporiZed.

    Eine fremde, nicht C# Anwendung davon abhalten mit Alt + F4 geschlossen zu werden. Ist es möglich?

    Hallo,

    ist es möglich, eine fremde Anwendung vom schließen via Alt + F4 abzuhalten?
    Ich würde dies gerne erzielen da ich gerne den Benutzer erst fragen möchte ob er diese Anwendung wirklich beenden möchte, da die Anwendung sonst immer sofort geschlossen wird.

    Kann man die Tastenkombination vielleicht in einem C# Programm abfangen and da dann weiter verarbeiten?

    Die Anwendung ist übrigens eine Vollbildanwendung.
    Wenn ich dir auf irgendeiner Art und Weise helfen konnte, drück doch bitte den "Hilfreich" Button :thumbup:

    Für VB.NET Entwickler: Option Strict On nicht vergessen!
    Ich habe einen systemweiten Hotkey für die Tastenkombi Alt+F4 registriert mit einem C# Programm.
    Aber was ist der nächste Schritt? Wie kann ich diese Tastenkombi "verwerfen" so das sie nicht mehr zur Vollbildanwendung gelangt?

    Das hört sich so an als ob das eher mit einer Sprache funtkionieren würde die "tiefer" ins System eingreift.
    Wenn ich dir auf irgendeiner Art und Weise helfen konnte, drück doch bitte den "Hilfreich" Button :thumbup:

    Für VB.NET Entwickler: Option Strict On nicht vergessen!
    Das passende Stichwort wurde dir doch schon gegeben !
    "Keyboard Hook", oder besser "Global Keyboard Hook" !

    Polemik an dieser Stelle entfernt ~VaporiZed

    Dieser Beitrag wurde bereits 1 mal editiert, zuletzt von „VaporiZed“ ()

    Ist ja gut, ich schrei hier auch nicht direkt so rum.
    Habs selbstständig herausgefunden.
    Wenn ich dir auf irgendeiner Art und Weise helfen konnte, drück doch bitte den "Hilfreich" Button :thumbup:

    Für VB.NET Entwickler: Option Strict On nicht vergessen!

    ClonkAndre schrieb:

    Habs selbstständig herausgefunden.
    Lässt Du uns an Deiner Lösung teilhaben?
    Falls Du diesen Code kopierst, achte auf die C&P-Bremse.
    Jede einzelne Zeile Deines Programms, die Du nicht explizit getestet hast, ist falsch :!:
    Ein guter .NET-Snippetkonverter (der ist verfügbar).
    Programmierfragen über PN / Konversation werden ignoriert!

    RodFromGermany schrieb:

    Lässt Du uns an Deiner Lösung teilhaben?

    Gerne.

    Dies ist die Klasse. Gefunden habe ich sie auf codeproject.
    Spoiler anzeigen

    C#-Quellcode

    1. using System;
    2. using System.Collections.Generic;
    3. using System.Runtime.InteropServices;
    4. using System.Windows.Forms;
    5. namespace PlayGTAIVOnline {
    6. /// <summary>
    7. /// A class that manages a global low level keyboard hook
    8. /// </summary>
    9. public class GlobalKeyboardHook {
    10. #region DLL imports
    11. /// <summary>
    12. /// Sets the windows hook, do the desired event, one of hInstance or threadId must be non-null
    13. /// </summary>
    14. /// <param name="idHook">The id of the event you want to hook</param>
    15. /// <param name="callback">The callback.</param>
    16. /// <param name="hInstance">The handle you want to attach the event to, can be null</param>
    17. /// <param name="threadId">The thread you want to attach the event to, can be null</param>
    18. /// <returns>a handle to the desired hook</returns>
    19. [DllImport("user32.dll")]
    20. static extern IntPtr SetWindowsHookEx(int idHook, keyboardHookProc callback, IntPtr hInstance, uint threadId);
    21. /// <summary>
    22. /// Unhooks the windows hook.
    23. /// </summary>
    24. /// <param name="hInstance">The hook handle that was returned from SetWindowsHookEx</param>
    25. /// <returns>True if successful, false otherwise</returns>
    26. [DllImport("user32.dll")]
    27. static extern bool UnhookWindowsHookEx(IntPtr hInstance);
    28. /// <summary>
    29. /// Calls the next hook.
    30. /// </summary>
    31. /// <param name="idHook">The hook id</param>
    32. /// <param name="nCode">The hook code</param>
    33. /// <param name="wParam">The wparam.</param>
    34. /// <param name="lParam">The lparam.</param>
    35. /// <returns></returns>
    36. [DllImport("user32.dll")]
    37. static extern int CallNextHookEx(IntPtr idHook, int nCode, int wParam, ref keyboardHookStruct lParam);
    38. /// <summary>
    39. /// Loads the library.
    40. /// </summary>
    41. /// <param name="lpFileName">Name of the library</param>
    42. /// <returns>A handle to the library</returns>
    43. [DllImport("kernel32.dll")]
    44. static extern IntPtr LoadLibrary(string lpFileName);
    45. /// <summary>
    46. /// Gets the state of modifier keys for a given keycode.
    47. /// </summary>
    48. /// <param name="keyCode">The keyCode</param>
    49. /// <returns></returns>
    50. [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true, CallingConvention = CallingConvention.Winapi)]
    51. private static extern short GetKeyState(int keyCode);
    52. #endregion
    53. #region Constant, Structure and Delegate Definitions
    54. /// <summary>
    55. /// defines the callback type for the hook
    56. /// </summary>
    57. public delegate int keyboardHookProc(int code, int wParam, ref keyboardHookStruct lParam);
    58. public struct keyboardHookStruct {
    59. public int vkCode;
    60. public int scanCode;
    61. public int flags;
    62. public int time;
    63. public int dwExtraInfo;
    64. }
    65. const int WH_KEYBOARD_LL = 13;
    66. const int WM_KEYDOWN = 0x100;
    67. const int WM_KEYUP = 0x101;
    68. const int WM_SYSKEYDOWN = 0x104;
    69. const int WM_SYSKEYUP = 0x105;
    70. //Modifier key vkCode constants
    71. private const int VK_SHIFT = 0x10;
    72. private const int VK_CONTROL = 0x11;
    73. private const int VK_MENU = 0x12;
    74. private const int VK_CAPITAL = 0x14;
    75. #endregion
    76. #region Instance Variables
    77. /// <summary>
    78. /// The collections of keys to watch for
    79. /// </summary>
    80. public List<Keys> HookedKeys = new List<Keys>();
    81. /// <summary>
    82. /// Handle to the hook, need this to unhook and call the next hook
    83. /// </summary>
    84. IntPtr hhook = IntPtr.Zero;
    85. #endregion
    86. #region Events
    87. /// <summary>
    88. /// Occurs when one of the hooked keys is pressed
    89. /// </summary>
    90. public event KeyEventHandler KeyDown;
    91. /// <summary>
    92. /// Occurs when one of the hooked keys is released
    93. /// </summary>
    94. public event KeyEventHandler KeyUp;
    95. #endregion
    96. #region Constructors and Destructors
    97. /// <summary>
    98. /// Initializes a new instance of the <see cref="globalKeyboardHook"/> class and installs the keyboard hook.
    99. /// </summary>
    100. public GlobalKeyboardHook() {
    101. Hook();
    102. }
    103. /// <summary>
    104. /// Releases unmanaged resources and performs other cleanup operations before the
    105. /// <see cref="globalKeyboardHook"/> is reclaimed by garbage collection and uninstalls the keyboard hook.
    106. /// </summary>
    107. ~GlobalKeyboardHook() {
    108. Unhook();
    109. }
    110. #endregion
    111. #region Public Methods
    112. /// <summary>
    113. /// Installs the global hook
    114. /// </summary>
    115. public void Hook() {
    116. IntPtr hInstance = LoadLibrary("User32");
    117. hhook = SetWindowsHookEx(WH_KEYBOARD_LL, hookProc, hInstance, 0);
    118. }
    119. /// <summary>
    120. /// Uninstalls the global hook
    121. /// </summary>
    122. public void Unhook() {
    123. UnhookWindowsHookEx(hhook);
    124. }
    125. /// <summary>
    126. /// The callback for the keyboard hook
    127. /// </summary>
    128. /// <param name="code">The hook code, if it isn't >= 0, the function shouldn't do anyting</param>
    129. /// <param name="wParam">The event type</param>
    130. /// <param name="lParam">The keyhook event information</param>
    131. /// <returns></returns>
    132. private int hookProc(int code, int wParam, ref keyboardHookStruct lParam) {
    133. if (code >= 0) {
    134. Keys key = (Keys)lParam.vkCode;
    135. if (HookedKeys.Contains(key)) {
    136. key = AddModifiers(key);
    137. KeyEventArgs kea = new KeyEventArgs(key);
    138. if ((wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN) && (KeyDown != null)) {
    139. KeyDown(this, kea) ;
    140. } else if ((wParam == WM_KEYUP || wParam == WM_SYSKEYUP) && (KeyUp != null)) {
    141. KeyUp(this, kea);
    142. }
    143. if (kea.Handled)
    144. return 1;
    145. }
    146. }
    147. return CallNextHookEx(hhook, code, wParam, ref lParam);
    148. }
    149. /// <summary>
    150. /// Checks whether Alt, Shift, Control or CapsLock
    151. /// is pressed at the same time as the hooked key.
    152. /// Modifies the keyCode to include the pressed keys.
    153. /// </summary>
    154. private Keys AddModifiers(Keys key)
    155. {
    156. //CapsLock
    157. if ((GetKeyState(VK_CAPITAL) & 0x0001) != 0) key = key | Keys.CapsLock;
    158. //Shift
    159. if ((GetKeyState(VK_SHIFT) & 0x8000) != 0) key = key | Keys.Shift;
    160. //Ctrl
    161. if ((GetKeyState(VK_CONTROL) & 0x8000) != 0) key = key | Keys.Control;
    162. //Alt
    163. if ((GetKeyState(VK_MENU) & 0x8000) != 0) key = key | Keys.Alt;
    164. return key;
    165. }
    166. #endregion
    167. }
    168. }



    Anwendung:
    Spoiler anzeigen

    C#-Quellcode

    1. private GlobalKeyboardHook globalKeyboardHook;
    2. public Main()
    3. {
    4. globalKeyboardHook = new GlobalKeyboardHook();
    5. globalKeyboardHook.HookedKeys.Add(System.Windows.Forms.Keys.Alt);
    6. globalKeyboardHook.HookedKeys.Add(System.Windows.Forms.Keys.F4);
    7. globalKeyboardHook.KeyDown += GlobalKeyboardHook_KeyDown;
    8. }
    9. private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    10. {
    11. globalKeyboardHook.KeyDown -= GlobalKeyboardHook_KeyDown;
    12. globalKeyboardHook.Unhook();
    13. }
    14. private void GlobalKeyboardHook_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
    15. {
    16. if (e.Alt && e.KeyCode == System.Windows.Forms.Keys.F4) { // Alt + F4
    17. // Check if window is open and maximized then prevent it from closing
    18. e.Handled = true;
    19. }
    20. }



    Dies funktioniert genau so wie ich das gerne möchte. Die Vollbildanwendung wird nicht mehr durch Alt + F4 geschlossen.
    Andere Anwendungen können zwar jetzt auch nicht mehr durch Alt + F4 geschlossen werden wenn der Hook aktiv ist, aber da habe ich eine Idee um dies zu verhindern.
    Wenn ich dir auf irgendeiner Art und Weise helfen konnte, drück doch bitte den "Hilfreich" Button :thumbup:

    Für VB.NET Entwickler: Option Strict On nicht vergessen!
    Reaktion auf Polemik an dieser Stelle entfernt ~VaporiZed

    Noch zum Thema vom Threadersteller:
    Es gibt da etwas ganz tolles, ich bin mir sicher es würde dir all dies ermöglichen und mit hoher Warscheinlichkeit noch mehr.
    Es gibt da dieses kleine Werkzeug mit dem Namen AutoHotKey, dafür schreibt man das eine oder andere Skriptchen.

    Mit jene welchen kannst du dann bestimmt so etwas in der Art bewerkstelligen.
    Das besondere, man findet bereits sehr sehr viele Skripte wenn man mal danach auf Google sucht.
    Ich bezweifle stark, dass es Dinge gibt die noch nicht jemand irgendwo im Internet veröffentlicht hat die für AHK bestimmt waren.

    Probiers einfach mal aus :D
    ----------------------------------------------------------------------------------------------------------------------

    Hier könnte meine Signatur stehen, aber die ist mir abfußen gekommen.

    ----------------------------------------------------------------------------------------------------------------------

    Dieser Beitrag wurde bereits 1 mal editiert, zuletzt von „VaporiZed“ ()

    Da damit zu rechnen ist, dass hier nicht mehr zum eigentlichen Thema beigetragen wird, wurde hier aufgeräumt und dichtgemacht. Führt Eure Diskussion notfalls in privater Konversation weiter.
    Dieser Beitrag wurde bereits 5 mal editiert, zuletzt von „VaporiZed“, mal wieder aus Grammatikgründen.

    Aufgrund spontaner Selbsteintrübung sind all meine Glaskugeln beim Hersteller. Lasst mich daher bitte nicht den Spekulatiusbackmodus wechseln.