如何显示动态创建的用户控件?

时间:2019-07-10 02:45:19

标签: c# winforms user-controls

我有一个名为home的用户控件,该控件已经设置了位置。当我在下面动态创建它时,看不到它。我尝试使用show将属性设置为visable并使用front方法,但是什么也没有。我想念什么?


    public class MainActivity {
        private MediaPlayerService player;
        boolean serviceBound = false;
        public static final String Broadcast_PLAY_NEW_AUDIO = "pkg_name.PlayNewAudio";
        //Binding this Client to the AudioPlayer Service
        private ServiceConnection serviceConnection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                // We've bound to LocalService, cast the IBinder and get LocalService instance
                MediaPlayerService.LocalBinder binder = (MediaPlayerService.LocalBinder) service;
                player = binder.getService();
                serviceBound = true;
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                serviceBound = false;
            }
        };

        // Call this method to play track
        public void playAudio(int audioIndex, ArrayList updatedList) {
            //Check is service is active
            audioList = updatedList;
            if (!serviceBound) {    
                Intent playerIntent = new Intent(this, MediaPlayerService.class);
                startService(playerIntent);
                bindService(playerIntent, serviceConnection, Context.BIND_AUTO_CREATE);
            } else {   
                //Service is active
                //Send a broadcast to the service -> PLAY_NEW_AUDIO
                Intent broadcastIntent = new Intent(Broadcast_PLAY_NEW_AUDIO);
                sendBroadcast(broadcastIntent);
            }

        }
        // Additional methods for control
        public void start() {
            player.playMedia();
        }
        public void pause() {
            player.pauseMedia();
        }
        public boolean isPlaying() {
            if (player != null && serviceBound) {
                return player.isPlaying();
            }
            return false;
        }
    }

1 个答案:

答案 0 :(得分:1)

在添加控件之前正在调用表单,将Application.Run(form);移动到函数的末尾。另外,我强烈建议在InitializeComponents();之后在表单构造函数中执行此操作,而不是在此处执行。