简体   繁体   中英

Cocoa performClick on button waiting for next external event

I have NSAlert instance which i run as modal for user confirmation on cancelling some operation. When user doesn't respond and the operations gets completed , i need to close this modal window. So, for this i'm calling performClick on default button in alert. But i observe that the perform click doesnt get executed instantly but waits for some external event such as mouse move event. Why is this happening? Apart from posting fake event, what are the other solutions?

Here is what you need to do.

Assumption:
1. IBAction is connect to NSButton Which will display the Alert View after clicking upon it.
2. It will perform Click operation by itself on the Second button of the Alert View.

Hope the below code will help you....

- (IBAction)showAlert:(id)sender
{
    //display the alert
    self.myAlert = [NSAlert alertWithMessageText:@"Sample Test" defaultButton:@"OK" alternateButton:@"DO Nothing" otherButton:@"CANCEL" informativeTextWithFormat:@"TEST",nil];
    [self.myAlert beginSheetModalForWindow:[self window]
                         modalDelegate:self
                        didEndSelector:@selector(errorAlertDidEnd:returnCode:contextInfo:)
                           contextInfo:nil];

    NSArray *buttonArray = [self.myAlert buttons];
    NSLog(@"Button Arrays %@",buttonArray);

    //Close by itself without a mouse click by the user
    //Assuming the Default Button as the Second one "Do Nothing
    NSButton *myBtn = [buttonArray objectAtIndex:2];
    [myBtn performClick:self.myAlert];
}


- (void)errorAlertDidEnd:(NSAlert *)alert returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo
{
    NSLog(@"TEST");
}

To know which button is clicked you can modify the mTo know which button is clicked you can modify the method errorAltertDidEnd

- (void)errorAlertDidEnd:(NSAlert *)alert returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo
{

   if(returnCode == NSAlertAlternateReturn)
   {
       NSLog(@"TEST Alternate %ld",returnCode);
   }

   if(returnCode == NSAlertDefaultReturn)
   {
       NSLog(@"TEST Default %ld",returnCode);
   }        
    if(returnCode == NSAlertOtherReturn)
    {
        NSLog(@"Test Other %ld",returnCode);
    }    
}

Could you please elaborate on this "But the click event(generated from performClick) itself waits for some external event(example: mouse move) –"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM