Windows get focused window

Содержание
  1. How do I get the title of the current active window using c#?
  2. 7 Answers 7
  3. Not the answer you’re looking for? Browse other questions tagged c# .net windows winforms or ask your own question.
  4. Linked
  5. Related
  6. Hot Network Questions
  7. Subscribe to RSS
  8. GetWindow function (winuser.h)
  9. Syntax
  10. Parameters
  11. Return value
  12. Remarks
  13. Window
  14. Synopsis
  15. Window.get([window_object])
  16. Window.getAll(callback)
  17. Window.open(url, [options], [callback])
  18. win.window
  19. win.width
  20. win.height
  21. win.title
  22. win.menu
  23. win.isAlwaysOnTop
  24. win.isFullscreen
  25. win.isTransparent
  26. win.isKioskMode
  27. win.zoomLevel
  28. win.cookies.*
  29. win.moveTo(x, y)
  30. win.moveBy(x, y)
  31. win.resizeTo(width, height)
  32. win.setInnerWidth(width)
  33. win.setInnerHeight(height)
  34. win.resizeBy(width, height)
  35. win.focus()
  36. win.blur()
  37. win.show([is_show])
  38. win.hide()
  39. win.close([force])
  40. win.reload()
  41. win.reloadDev()
  42. win.reloadIgnoringCache()
  43. win.maximize()
  44. win.unmaximize()
  45. win.minimize()
  46. win.restore()
  47. win.enterFullscreen()
  48. win.leaveFullscreen()
  49. win.toggleFullscreen()
  50. win.enterKioskMode()
  51. win.leaveKioskMode()
  52. win.toggleKioskMode()
  53. win.setTransparent(transparent)
  54. win.setShadow(shadow) (Mac)
  55. win.showDevTools([iframe], [callback])
  56. win.closeDevTools()
  57. win.getPrinters(callback)
  58. win.isDevToolsOpen()
  59. win.print(options)
  60. win.setMaximumSize(width, height)
  61. win.setMinimumSize(width, height)
  62. win.setResizable(resizable)
  63. win.setAlwaysOnTop(top)
  64. win.setVisibleOnAllWorkspaces(visible) (Mac and Linux)
  65. win.canSetVisibleOnAllWorkspaces() (Mac and Linux)
  66. win.setPosition(position)
  67. win.setShowInTaskbar(show)
  68. win.requestAttention(attension)
  69. win.capturePage(callback [, config ])
  70. win.captureScreenshot(options [, callback])
  71. win.setProgressBar(progress)
  72. win.setBadgeLabel(label)
  73. win.eval(frame, script)
  74. win.evalNWBin(frame, path)
  75. win.evalNWBinModule(frame, path, module_path)
  76. win.removeAllListeners([eventName])
  77. Event: close
  78. Event: closed
  79. Event: loading
  80. Event: loaded
  81. Event: document-start(frame)
  82. Event: document-end(frame)
  83. Event: focus
  84. Event: blur
  85. Event: minimize
  86. Event: restore
  87. Event: maximize
  88. Event: move(x, y)
  89. Event: resize(width, height)
  90. Event: enter-fullscreen
  91. Event: leave-fullscreen
  92. Event: zoom
  93. Event: capturepagedone
  94. Event: devtools-opened(url)
  95. Event: devtools-closed
  96. Event: new-win-policy (frame, url, policy)

How do I get the title of the current active window using c#?

I’d like to know how to grab the Window title of the current active window (i.e. the one that has focus) using C#.

7 Answers 7

See example on how you can do this with full source code here:

Edited with @Doug McClean comments for better correctness.

If you were talking about WPF then use:

It supports UTF8 characters.

Loop over Application.Current.Windows[] and find the one with IsActive == true .

Use the Windows API. Call GetForegroundWindow() .

GetForegroundWindow() will give you a handle (named hWnd ) to the active window.

If it happens that you need the Current Active Form from your MDI application: (MDI- Multi Document Interface).

you can use process class it’s very easy. use this namespace

if you want to make a button to get active window.

Not the answer you’re looking for? Browse other questions tagged c# .net windows winforms or ask your own question.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.4.16.39093

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

GetWindow function (winuser.h)

Retrieves a handle to a window that has the specified relationship (Z-Order or owner) to the specified window.

Syntax

Parameters

A handle to a window. The window handle retrieved is relative to this window, based on the value of the uCmd parameter.

The relationship between the specified window and the window whose handle is to be retrieved. This parameter can be one of the following values.

Value Meaning
GW_CHILD 5 The retrieved handle identifies the child window at the top of the Z order, if the specified window is a parent window; otherwise, the retrieved handle is NULL. The function examines only child windows of the specified window. It does not examine descendant windows.
GW_ENABLEDPOPUP 6 The retrieved handle identifies the enabled popup window owned by the specified window (the search uses the first such window found using GW_HWNDNEXT); otherwise, if there are no enabled popup windows, the retrieved handle is that of the specified window.
GW_HWNDFIRST 0 The retrieved handle identifies the window of the same type that is highest in the Z order.

If the specified window is a topmost window, the handle identifies a topmost window. If the specified window is a top-level window, the handle identifies a top-level window. If the specified window is a child window, the handle identifies a sibling window.

GW_HWNDLAST 1 The retrieved handle identifies the window of the same type that is lowest in the Z order.

If the specified window is a topmost window, the handle identifies a topmost window. If the specified window is a top-level window, the handle identifies a top-level window. If the specified window is a child window, the handle identifies a sibling window.

GW_HWNDNEXT 2 The retrieved handle identifies the window below the specified window in the Z order.

If the specified window is a topmost window, the handle identifies a topmost window. If the specified window is a top-level window, the handle identifies a top-level window. If the specified window is a child window, the handle identifies a sibling window.

GW_HWNDPREV 3 The retrieved handle identifies the window above the specified window in the Z order.

If the specified window is a topmost window, the handle identifies a topmost window. If the specified window is a top-level window, the handle identifies a top-level window. If the specified window is a child window, the handle identifies a sibling window.

GW_OWNER 4 The retrieved handle identifies the specified window’s owner window, if any. For more information, see Owned Windows.

Return value

If the function succeeds, the return value is a window handle. If no window exists with the specified relationship to the specified window, the return value is NULL. To get extended error information, call GetLastError.

Remarks

The EnumChildWindows function is more reliable than calling GetWindow in a loop. An application that calls GetWindow to perform this task risks being caught in an infinite loop or referencing a handle to a window that has been destroyed.

Window

Window is a wrapper of the DOM’s topmost window object. It has extended operations and can receive various window events.

Every Window is an instance of the EventEmitter class, and you’re able to use Window.on(. ) to respond to native window’s events.

There are some changes of Window since 0.13.0. Please see Migration Notes from 0.12 to 0.13.

Synopsis

Window.get([window_object])

  • window_object Optional is the DOM window
  • Returns the native Window object

If window_object is not specifed, then return current window’s Window object, otherwise return window_object ‘s Window object.

If window_object is iframe ‘s, the function will still return topmost window’s Window object.

Window.getAll(callback)

Get all windows with a callback function whose parameter is an array of nw.Window object. This function is supported since 0.42.6.

Window.open(url, [options], [callback])

The behavior of the function is changed since 0.13.0. Please see Migration Notes from 0.12 to 0.13.

  • url URL to be loaded in the opened window
  • options Optional see Window subfields in manifest format. And following extra fields can also be used in options.
    • new_instance Optional whether to open a new window in a separate render process.
    • mixed_context Optional If true, the Node context and DOM context are merged in the new window’s process. Use only when new_instance is true.
    • inject_js_start Optional the script to be injected before any DOM is constructed and any script is run. See Manifest format
    • inject_js_end Optional the script to be injected after the document object is loaded, before onload event is fired. See Manifest format
    • id Optional the id used to identify the window. This will be used to remember the size and position of the window and restore that geometry when a window with the same id is later opened. See also the Chrome App documentation
  • callback(win) Optional callback when with the opened native Window object
  • Open a new window and load url in it.

    You should wait for the Window’s loaded event before interacting with any of its components.

    The opened window is not focused by default. If you want it to be focused by default, you can set focus to true in options .

    win.window

    Get the corresponding DOM window object of the native window.

    Get or set left/top offset from window frame to screen.

    win.width

    win.height

    Get or set window’s size, including the window’s frame.

    win.title

    Get or set window’s title.

    win.menu

    Get or set window’s menubar. Set with a Menu with type menubar . When win.menu is set to null , the menubar is completely removed for Windows and Linux, and the menubar is cleared out on Mac.

    See Customize Menubar for the usage of menubars. And see Menu and MenuItem for detailed APIs.

    win.isAlwaysOnTop

    Get whether the window is always on top of other windows.

    win.isFullscreen

    Get whether we’re in fullscreen mode.

    win.isTransparent

    Get whether transparency is turned on

    win.isKioskMode

    Get whether we’re in kiosk mode.

    win.zoomLevel

    Get or set the page zoom. 0 for normal size; positive value for zooming in; negative value for zooming out.

    win.cookies.*

    This includes multiple functions to manipulate the cookies. The API is defined in the same way as Chrome Extensions. NW.js supports the get , getAll , remove and set methods; onChanged event (supporting both addListener and removeListener function on this event).

    And anything related to CookieStore in the Chrome extension API is not supported, because there is only one global cookie store in NW.js apps.

    win.moveTo(x, y)

    • x offset to the left of the screen
    • y offset to the top of the screen

    Moves a window’s left and top edge to the specified coordinates.

    win.moveBy(x, y)

    • x horizontal offset
    • y vertical offset

    Moves a window a specified number of pixels relative to its current coordinates.

    win.resizeTo(width, height)

    • width the inner width of the window
    • height the inner height of the window

    Resizes a window to the specified width and height .

    win.setInnerWidth(width)

    • width the inner width of the window

    win.setInnerHeight(height)

    • height the inner height of the window

    win.resizeBy(width, height)

    • width the offset width of the window
    • height the offset height of the window

    Resizes a window by the specified amount.

    win.focus()

    Focus on the window.

    win.blur()

    Move focus away. Usually it will move focus to other windows of your app, since on some platforms there is no concept of blur.

    win.show([is_show])

    • is_show Optional specify whether the window should be shown or hidden. It’s set to true by default.

    Show the window if it’s not shown.

    show(false) has the same effect with hide() .

    show will not focus on the window on some platforms, so you need to call focus if you want to.

    win.hide()

    Hide the window. User will not be able to find the window once it’s hidden.

    win.close([force])

    • force specify whether to close the window forcefully and bypass the close event.

    Closes the current window. You can prevent the closing by listening to the close event. If force is specified and equals true , then the close event will be ignored.

    Usually you would like to listen to the close event and do some shutdown work and then do a close(true) to really close the window.

    win.reload()

    Reloads the current window.

    win.reloadDev()

    Reloads the current page by starting a new renderer process from scratch.

    win.reloadIgnoringCache()

    Like reload() , but don’t use caches (aka “shift-reload”).

    win.maximize()

    Maximize the window on GTK and Windows, and zoom the window on Mac OS X.

    win.unmaximize()

    This feature is deprecated since 0.13.0. It’s now replaced by restore event. See Migration Notes from 0.12 to 0.13.

    Unmaximize the window, i.e. the reverse of maximize() .

    win.minimize()

    Minimize the window to task bar on Windows, iconify the window on GTK, and miniaturize the window on Mac OS X.

    win.restore()

    Restore window to previous state after the window is minimized, i.e. the reverse of minimize() . It’s not named unminimize since restore is used commonly.

    win.enterFullscreen()

    Make the window fullscreen.

    This function is different with HTML5 FullScreen API, which can make part of the page fullscreen, Window.enterFullscreen() will only fullscreen the whole window.

    win.leaveFullscreen()

    Leave the fullscreen mode.

    win.toggleFullscreen()

    Toggle the fullscreen mode.

    win.enterKioskMode()

    Enter the Kiosk mode. In Kiosk mode, the app will be fullscreen and try to prevent users from leaving the app, so you should remember to provide a way in app to leave Kiosk mode. This mode is mainly used for presentation on public displays.

    win.leaveKioskMode()

    Leave the Kiosk mode.

    win.toggleKioskMode()

    Toggle the kiosk mode.

    win.setTransparent(transparent)

    This feature is deprecated since 0.13.0. See Migration Notes from 0.12 to 0.13.

    • transparent whether to set the window to be transparent

    Turn on/off the transparency support. See more info on Transparent Window.

    win.setShadow(shadow) (Mac)

    • shadow whether the window has a shadow

    Turn the window’s native shadow on/off. Useful for frameless, transparent windows.

    win.showDevTools([iframe], [callback])

    This API is only available on SDK build flavor.

    The behavior of the function is changed since 0.13.0. Please see Migration Notes from 0.12 to 0.13.

    • iframe or Optional the id or the element of the to be jailed on. By default, the DevTools is shown for entire window.
    • callback(dev_win) callback with the native window of the DevTools window.

    Open the devtools to inspect the window.

    The optional iframe as String should be the value of id attribute of any element in the window. It jails the DevTools to inspect the only. If it is an empty string, this feature has no effect.

    The optional iframe as HTMLIFrameElement should be the iframe object. And it serves the same purpose with the id argument.

    This function returns a Window object via the callback. You can use any properties and methods of Window except the events.

    See also in webview reference on how to open DevTools for webview or open DevTools in a webview.

    win.closeDevTools()

    This API is only available on SDK build flavor.

    Close the devtools window.

    win.getPrinters(callback)

    Enumerate the printers in the system. The callback function will receive an array of JSON objects for the printer information. The device name of the JSON object can be used as parameter in nw.Window.print() .

    win.isDevToolsOpen()

    This API is only available on SDK build flavor.

    Query the status of devtools window.

    win.print(options)

    Print the web contents in the window with or without the need for user’s interaction. options is a JSON object with the following fields:

    • autoprint whether to print without the need for user’s interaction; optional, true by default
    • silent hide the flashing print preview dialog; optional, false by default
    • printer the device name of the printer returned by nw.Window.getPrinters() ; No need to set this when printing to PDF
    • pdf_path the path of the output PDF when printing to PDF
    • headerFooterEnabled whether to enable header and footer
    • landscape whether to use landscape or portrait
    • mediaSize the paper size spec
    • shouldPrintBackgrounds whether to print CSS backgrounds
    • marginsType 0 — Default; 1 — No margins; 2 — minimum; 3 — Custom, see marginsCustom .
    • marginsCustom the custom margin setting; units are points.
    • copies the number of copies to print.
    • scaleFactor the scale factor; 100 is the default.
    • headerString string to replace the URL in the header.
    • footerString string to replace the URL in the footer.

    NOTE: If no options are being passed, win.print(<>) is what should be called.

    win.setMaximumSize(width, height)

    • width the maximum width of the window
    • height the maximum height of the window

    Set window’s maximum size.

    win.setMinimumSize(width, height)

    • width the minimum width of the window
    • height the minimum height of the window

    Set window’s minimum size.

    win.setResizable(resizable)

    • resizable whether the window can be resized

    Set whether window is resizable.

    win.setAlwaysOnTop(top)

    • top whether the window should always be on top

    Sets the widget to be on top of all other windows in the window system.

    win.setVisibleOnAllWorkspaces(visible) (Mac and Linux)

    • visible whether the window should be visible on all workspaces

    For platforms that support multiple workspaces (currently Mac OS X and Linux), this allows NW.js windows to be visible on all workspaces simultaneously.

    win.canSetVisibleOnAllWorkspaces() (Mac and Linux)

    Returns a a boolean indicating if the platform (currently Mac OS X and Linux) support Window API method setVisibleOnAllWorkspace(Boolean) .

    win.setPosition(position)

    • position the position of the window. There are three valid positions: null or center or mouse

    Move window to specified position. Currently only center is supported on all platforms, which will put window in the middle of the screen.

    win.setShowInTaskbar(show)

    Control whether to show window in taskbar or dock. See also show_in_taskbar in Manifest-format.

    win.requestAttention(attension)

    • attension or If a Boolean, it indicates to request or cancel user’s attension. If an Integer, it indicates the number of times the window flashes.

    Request the user’s attension by making the window flashes in the task bar.

    On Mac, value NSInformationalRequest , while value > 0 will trigger NSCriticalRequest .

    win.capturePage(callback [, config ])

    • callback the callback when finished capturing the window
    • config or Optional if a String, see config.format for valid values.
      • format optional the image format used to generate the image. It supports two formats: «png» and «jpeg» . If ignored, it’s «jpeg» by default.
      • datatype it supports three types: «raw» , «buffer» and «datauri» . If ignored, it’s «datauri» by default.

      Captures the visible area of the window. To capture the full page, see win.captureScreenshot .

      The «raw» only contains the Base64 encoded image. But «datauri» contains the mime type headers as well, and it can be directly assigned to src of Image to load the image.

      win.captureScreenshot(options [, callback])

      When callback is omitted, a Promise is returned and it will resolve with data argument of the callback.

      • callback optional the callback when finished capturing the window. It’s called with:
        • err null for success; with the error message for failure.
        • data base64 encoded image
      • options
        • fullSize optional Capture the whole page beyond the visible area. Currently the height of captured image is capped at 16384 pixels by Chromium.
        • format optional the image format used to generate the image. It supports two formats: «png» and «jpeg» . «png» is the default.
        • quality optional Compression quality from range [0..100] (jpeg only).
        • clip optional Capture the screenshot of a given region only. The object’s properties are:
        • x : X offset in device independent pixels (dip).
        • y : Y offset in device independent pixels (dip).
        • width : Rectangle width in device independent pixels (dip).
        • height : Rectangle height in device independent pixels (dip).
        • scale : Page scale factor.
        • Captures the the window. It can be used to capture the full page beyond the visible area.

          This API is experimental and subject to change in the future.

          win.setProgressBar(progress)

          • progress valid values within [0, 1]. Setting to negative value ( .desktop file through NW_DESKTOP env. If NW_DESKTOP env variable is not found, it uses nw.desktop by default.

          win.setBadgeLabel(label)

          Set the badge label on the window icon in taskbar or dock.

          This API is only supported on Ubuntu and the label is restricted to a string number only. You’ll also need to specify the .desktop file for your application (see the note on setProgressBar )

          win.eval(frame, script)

          • frame the frame to execute in. If iframe is null , it assumes in current window / frame.
          • script the source code of the script to be executed

          Execute a piece of JavaScript in the frame.

          win.evalNWBin(frame, path)

          • frame the frame to execute in. If iframe is null , it assumes in current window / frame.
          • path the path or Buffer or ArrayBuffer of the binary file generated by nwjc

          Load and execute the compiled binary in the frame. See Protect JavaScript Source Code.

          win.evalNWBinModule(frame, path, module_path)

          This API is subject to change in future versions as we’re exploring ways to support this feature better. Discuss here.

          • frame the frame to execute in. If iframe is null , it assumes in current window / frame.
          • path the path or Buffer or ArrayBuffer of the binary file generated by nwjc
          • module_path the module URL related to the current document. It will be used to resolve the module specifier.

          Load and execute the compiled binary for Modules in the frame. The binary should be compiled with nwjc —nw-module . The following code will load lib.bin as module and other modules can refer to it with something like import * from ‘./lib.js’ :

          win.removeAllListeners([eventName])

          Removes all listeners, or those of the specified eventName .

          Event: close

          The close event is a special event that will affect the result of the Window.close() function. If developer is listening to the close event of a window, the Window.close() emit the close event without closing the window.

          Usually you would do some shutdown work in the callback of close event, and then call this.close(true) to really close the window, which will not be caught again. Forgetting to add true when calling this.close() in the callback will result in infinite loop.

          And if the shutdown work takes some time, users may feel that the app is exiting slowly, which is bad experience, so you could just hide the window in the close event before really closing it to make a smooth user experience.

          See example code of win.close(true) above for the usage of close event.

          On Mac, there is an argument passed to the callback indicating whether it’s being closed by ⌘ + Q . It will be set to string quit if that’s true, otherwise undefined .

          Event: closed

          The closed event is emitted after the corresponding window is closed. Normally you will not be able to get this event since after the window is closed all js objects will be released. But it is useful when listening to the window’s events in another window, whose objects will not be released.

          Event: loading

          Emitted when the window starts to reload, normally you cannot catch this event because usually it’s emitted before you actually setup the callback.

          The only situation that you can catch this event is when you refresh the window and listen to this event in another window.

          Event: loaded

          Emitted when the window is fully loaded, this event behaves the same with window.onload , but doesn’t rely on the DOM.

          Event: document-start(frame)

          • frame is the iframe object, or null if the event is for the window.

          Emitted when the document object in this window or a child iframe is available, after all files are loaded, but before DOM is constructed or any script is run.
          It will not be fired on the new window being created with nw.Window.open(): the callback of that function will be fired at the same point of this event.

          See inject_js_start in Manifest-format.

          Event: document-end(frame)

          • frame is the iframe object, or null if the event is for the window.

          Emitted when the document object in this window or a child iframe is unloaded, but before the onunload event is emitted.

          See inject_js_end in Manifest-format

          Event: focus

          Emitted when window gets focus.

          Event: blur

          Emitted when window loses focus.

          Event: minimize

          Emitted when window is minimized.

          Event: restore

          The behavior of the function is changed since 0.13.0. Please see Migration Notes from 0.12 to 0.13.

          Emitted when window is restored from minimize, maximize and fullscreen state.

          Event: maximize

          Emitted when window is maximized.

          Event: move(x, y)

          Emitted after window is moved. The callback is called with 2 arguments: (x, y) for the new location of the left / top corner of the window.

          Event: resize(width, height)

          Emitted after window is resized. The callback is called with 2 arguments: (width, height) for the new size of the window.

          Event: enter-fullscreen

          Emitted when window enters fullscreen state.

          Event: leave-fullscreen

          This feature is deprecated since 0.13.0. It’s now replaced by restore event. See Migration Notes from 0.12 to 0.13.

          Emitted when window leaves fullscreen state.

          Event: zoom

          Emitted when window zooming changed. It has a parameter indicating the new zoom level. See win.zoom() method for the parameter’s value definition.

          Event: capturepagedone

          This feature is deprecated since 0.13.0. Use the callback with win.capturePage() instead. See Migration Notes from 0.12 to 0.13.

          Emitted after the capturePage method is called and image data is ready. See win.capturePage() callback function for the parameter’s value definition.

          Event: devtools-opened(url)

          This feature is deprecated since 0.13.0. Use the callback passed to win.showDevtools instead. See Migration Notes from 0.12 to 0.13.

          Event: devtools-closed

          Emitted after Devtools is closed.

          Event: new-win-policy (frame, url, policy)