R – Textfield () – how to prevent mouse right click menu

actionscript-3flex3

Textfield () – how to prevent mouse right click menu from appearing (a menu having COPY, PASTE, SELECT ALL etc options).

Best Answer

FlashPlayers default menu items.

As far as I know you cannot remove the basic FlashPlayer items (Settings and About) which make sense.

FlashPlayers inbuilt items

You can remove the top ones (Play, Pause, etc.) by either specifying it while compiling or from within the code:

contextMenu.hideBuiltInItems();

or within the global context :

stage.showDefaultContextMenu = false; 

TextField related menu items

The copy/paste/select being inbuilt as well for TextFields it doesn't seem you can hide them. However as it seems like you really want to get rid of them here's a workaround. The example below illustrates how you can add a transparent button over the textField to sidetrack the mouse behavior:

package  
{
    import flash.display.Sprite;
    import flash.display.Stage;
    import flash.events.MouseEvent;
    import flash.text.TextField;
    import flash.text.TextFieldType;
    import flash.ui.ContextMenu;        


    public class TestText extends Sprite 
    {

        private var textField:TextField;

        public function TestText()
        {
            // Removes the inbuit items from the contextMenu

            var contextMenu:ContextMenu = new ContextMenu();
            contextMenu.hideBuiltInItems();
            this.contextMenu = contextMenu;

            // Adds a simple input TextField

            textField = addChild(new TextField()) as TextField;
            textField.type = TextFieldType.INPUT;
            textField.text = "Test Text";

            // Covers the TextField with a transparent shape

            var shape:Sprite = addChild(new Sprite()) as Sprite;
            shape.graphics.beginFill(0, 0);
            shape.graphics.drawRect(0, 0, textField.width, textField.height);
            shape.mouseChildren = false;

            // Listens to a click on the mask to activate typing

            shape.addEventListener(MouseEvent.CLICK, eventClickHandler);
        }

        private function eventClickHandler(event:MouseEvent):void
        {
            // Sets the focus to the underlaying TextField and makes 
            // a full selection of the existing text.

            stage.focus = textField;
            textField.setSelection(0, textField.text.length);
        }
    }
}
Related Topic