4
$\begingroup$

How could I detect if a notebook is currently the active window?

This is what I have tried, but it does not work as the value of x is never updated:

EventHandler[
 CreateDocument[
  {TextCell["Window status:", "Text"],
   ExpressionCell[Dynamic[x], "Output"]}],
 {"FocusGained" :> (x = "This window is active"),
  "FocusLost" :> (x = "This window is not active")}]

UPDATE: With the help of Carl's answer, I would like to share the motivation for the question. Without the Enable part, using the FileNameSetter (without making the window active first) would produce a "INTERNAL SELF-TEST ERROR: winModality|c|511" (CASE:4033279). Now I can avoid it:

CreateDocument[{ExpressionCell[
    Dynamic[
        FileNameSetter[Dynamic[f],
            Enabled -> SelectedNotebook[] === EvaluationNotebook[]]], 
    "Output"]}, WindowSelected -> False]
$\endgroup$
6
$\begingroup$

You could try something like:

CreateDocument[{
    TextCell["Window status:", "Text"],
    ExpressionCell[
        Dynamic[SelectedNotebook[]===EvaluationNotebook[], UpdateInterval->1],
        "Output"
    ]
}]

Here's an animation:

enter image description here

$\endgroup$
1
  • 1
    $\begingroup$ Might be more convenient in the NotebookDynamicExpression. Or bound to the MouseEntered and MouseExited events. $\endgroup$
    – b3m2a1
    Jun 7 '18 at 0:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.