<!--
{
  "availability" : [
    "macOS: -"
  ],
  "documentType" : "symbol",
  "framework" : "AppKit",
  "identifier" : "/documentation/AppKit/NSApplication/beginModalSession(for:)",
  "metadataVersion" : "0.1.0",
  "role" : "Instance Method",
  "symbol" : {
    "kind" : "Instance Method",
    "modules" : [
      "AppKit"
    ],
    "preciseIdentifier" : "c:objc(cs)NSApplication(im)beginModalSessionForWindow:"
  },
  "title" : "beginModalSession(for:)"
}
-->

# beginModalSession(for:)

Sets up a modal session with the given window and returns a pointer to the `NSModalSession` structure representing the session.

```
func beginModalSession(for window: NSWindow) -> NSApplication.ModalSession
```

## Parameters

`window`

The window for the session.

## Return Value

A pointer to the `NSModalSession` structure that represents the session.

## Discussion

In a modal session, the app receives mouse events only if they occur in `aWindow`. The window is made key, and if not already visible is placed onscreen using the `NSWindow` method [`center()`](/documentation/AppKit/NSWindow/center()).

The [`beginModalSession(for:)`](/documentation/AppKit/NSApplication/beginModalSession(for:)) method only sets up the modal session. To actually run the session, use [`runModalSession(_:)`](/documentation/AppKit/NSApplication/runModalSession(_:)). [`beginModalSession(for:)`](/documentation/AppKit/NSApplication/beginModalSession(for:)) should be balanced by [`endModalSession(_:)`](/documentation/AppKit/NSApplication/endModalSession(_:)). Make sure these two messages are sent within the same exception-handling scope. That is, if you send [`beginModalSession(for:)`](/documentation/AppKit/NSApplication/beginModalSession(for:)) inside an `NS_DURING` construct, you must send [`endModalSession(_:)`](/documentation/AppKit/NSApplication/endModalSession(_:)) before `NS_ENDHANDLER`.

If an exception is raised, [`beginModalSession(for:)`](/documentation/AppKit/NSApplication/beginModalSession(for:)) arranges for proper cleanup. Do not use `NS_DURING` constructs to send an [`endModalSession(_:)`](/documentation/AppKit/NSApplication/endModalSession(_:)) message in the event of an exception.

A loop using these methods is similar to a modal event loop run with [`runModal(for:)`](/documentation/AppKit/NSApplication/runModal(for:)), except the app can continue processing between method invocations.

---

Copyright &copy; 2026 Apple Inc. All rights reserved. | [Terms of Use](https://www.apple.com/legal/internet-services/terms/site.html) | [Privacy Policy](https://www.apple.com/privacy/privacy-policy)