flash on 2014-6-14

by tepe
カーソル位置にある文字を取得する
♥0 | Line 50 | Modified 2014-06-21 14:08:25 | MIT License
play

ActionScript3 source code

/**
 * Copyright tepe ( http://wonderfl.net/user/tepe )
 * MIT License ( http://www.opensource.org/licenses/mit-license.php )
 * Downloaded from: http://wonderfl.net/c/hKC5
 */

//カーソル位置にある文字を取得する
package {
    import flash.display.Sprite;
    import flash.events.*;
    import flash.text.*;
    public class FlashTest extends Sprite {
        private var tf:TextField = new TextField();
        private var tf2:TextField = new TextField();
        public function FlashTest() {
            // write as3 code here..
            addChild(tf);
            addChild(tf2);
            tf2.x = 200;
            tf.text = "test";
            tf.type="input";
            tf.multiline=true;
            tf.border = true;
            tf.addEventListener(MouseEvent.MOUSE_MOVE,onMove);
            tf.addEventListener(KeyboardEvent.KEY_UP,onKey);
        }
        private function onMove(e:MouseEvent):void{
            var n:int = tf.getCharIndexAtPoint(mouseX,mouseY);
            //tf2.text = n.toString();
            var str:String = tf.text;
            tf2.text = str.charAt(n)+"\n";
            var line:int = tf.getLineIndexAtPoint(e.currentTarget.mouseX,e.currentTarget.mouseY);//指定位置の文字
            tf2.appendText(tf.getLineText(line)+"\n");//指定行の文字列
            tf2.appendText(tf.selectionBeginIndex.toString());
            if(tf.selectionBeginIndex!=tf.selectionEndIndex){ 
                tf2.appendText("-"+tf.selectionEndIndex.toString()+"\n");
            }
            tf2.appendText(getSelectedText(tf));
        }
        
        private function onKey(e:KeyboardEvent):void{
            var n:int = tf.getCharIndexAtPoint(mouseX,mouseY);
            //tf2.text = n.toString();
            var str:String = tf.text;
            tf2.text = str.charAt(n)+"\n";
            tf2.appendText(tf.selectionBeginIndex.toString());
            if(tf.selectionBeginIndex!=tf.selectionEndIndex){ 
                tf2.appendText("-"+tf.selectionEndIndex.toString()+"\n");
            }
            tf2.appendText(getSelectedText(tf));
        }
        //選択範囲の文字列を取得する
        public function getSelectedText(ft:TextField):String{
            var str:String = tf.text;
            var result:String;
            if(tf.selectionBeginIndex!=tf.selectionEndIndex){ 
                result = str.substring(tf.selectionBeginIndex,tf.selectionEndIndex);
            }
            return result;
        }


    }
}