예를 들어 MP3 리더의 앞으로 버튼과 같이 오랫동안 Button
을 누르면 동작을 반복하고 싶습니다. WinForm에 기존 C# 이벤트가 있습니까?길게 눌린 버튼
나는 작업을 수행하고 MouseUp
이벤트를 중지 타이머를 시작합니다 MouseDown
이벤트를 처리 할 수 있지만, 나는이 문제 => 즉, 해결하는 쉬운 방법을 찾고 있는데요하십시오 Timer
없이 솔루션을 (또는 스레드/작업 ...).
예를 들어 MP3 리더의 앞으로 버튼과 같이 오랫동안 Button
을 누르면 동작을 반복하고 싶습니다. WinForm에 기존 C# 이벤트가 있습니까?길게 눌린 버튼
나는 작업을 수행하고 MouseUp
이벤트를 중지 타이머를 시작합니다 MouseDown
이벤트를 처리 할 수 있지만, 나는이 문제 => 즉, 해결하는 쉬운 방법을 찾고 있는데요하십시오 Timer
없이 솔루션을 (또는 스레드/작업 ...).
MouseDown과 MouseUp 사이에서 타이머를 사용할 수 있습니다.
MouseDownEvent
Timer tm1;
MouseUpEvent
Timer tm2;
두 타이머간에 쉽게 처리 할 수 있습니다.
MP3 트랙에서 몇 초를 건너 뛰는 것처럼 버튼을 누르고있는 동안 어떤 동작을 수행해야합니다.
버튼을 누르고있는 동안 일정한 간격 (100ms?)으로 그런 종류의 작업을 트리거하는 mouseUp에서 타이머를 시작하는 것이 가능합니다. 구현하기 쉽고 UI에서 차단되지 않습니다.
더 간단한 해결책을 사용하면 UI가 차단 될 수 있습니다.
업데이트 : 최단 방법 :
는 Anonymous Methods
및 Object Initializer
사용 :
public void Repeater(Button btn, int interval)
{
var timer = new Timer {Interval = interval};
timer.Tick += (sender, e) => DoProgress();
btn.MouseDown += (sender, e) => timer.Start();
btn.MouseUp += (sender, e) => timer.Stop();
btn.Disposed += (sender, e) =>
{
timer.Stop();
timer.Dispose();
};
}
내가 작업을 수행하고 MouseUp 이벤트에 중단됩니다 타이머를 시작 MouseDown 이벤트를 처리 할 수 있지만, 이 문제를 해결하기위한 쉬운 방법은 입니다..
재사용 가능한 방식으로 한 번 쓰면 쉽게 만들 수 있습니다. 이 동작을하는 자신의 Button
클래스를 파생시킬 수 있습니다.
또는 임의의 단추에 연결할 수있는 클래스를 작성하여이 동작을 부여 할 수 있습니다. 다음과 같이
는class ButtonClickRepeater
{
public event EventHandler Click;
private Button button;
private Timer timer;
public ButtonClickRepeater(Button button, int interval)
{
if (button == null) throw new ArgumentNullException();
this.button = button;
button.MouseDown += new MouseEventHandler(button_MouseDown);
button.MouseUp += new MouseEventHandler(button_MouseUp);
button.Disposed += new EventHandler(button_Disposed);
timer = new Timer();
timer.Interval = interval;
timer.Tick += new EventHandler(timer_Tick);
}
void button_MouseDown(object sender, MouseEventArgs e)
{
OnClick(EventArgs.Empty);
timer.Start();
}
void button_MouseUp(object sender, MouseEventArgs e)
{
timer.Stop();
}
void button_Disposed(object sender, EventArgs e)
{
timer.Stop();
timer.Dispose();
}
void timer_Tick(object sender, EventArgs e)
{
OnClick(EventArgs.Empty);
}
protected void OnClick(EventArgs e)
{
if (Click != null) Click(button, e);
}
}
당신은 다음을 사용 : 예를 들어, 당신은 같은 것을 할 수
private void Form1_Load(object sender, EventArgs e)
{
ButtonClickRepeater repeater = new ButtonClickRepeater(this.myButton, 1000);
repeater.Click += new EventHandler(repeater_Click);
}
이상 간결하게, 당신은 ButtonClickRepeater
에 대한 참조를 유지할 필요가 없기 때문에 :
private void Form1_Load(object sender, EventArgs e)
{
new ButtonClickRepeater(this.myBbutton, 1000).Click += new EventHandler(repeater_Click);
}
MouseUp에서도 Tick 이벤트를 구독 취소하는 것이 좋습니다. –
또한 타이머를 폐기하는 것을 잊지 마십시오. – Joe
당신은'Timer'를 사용하고 있습니다. 익명 메소드는 실제 메소드를 쓰는 대신에 가장 짧은 방법 일뿐입니다. 이것이 Framework 4.0에 존재하지 않습니까? –