2013-11-21 4 views
0

У меня есть чек Собирается каждые 60 секунд, если тревога правда она будет открыта form2 играть песню и т.д.Попытка изменить таймер один раз была нажата кнопка

но кнопка на form2 следует установить waittimer = 180000, который должен сделать следующую проверку, происходит через полчаса позже.

Я не привык использовать таймеры, что я делаю неправильно?

Public Class Form1 
Public Property waittimer As Integer 
Public Property playsong As Boolean = True 
Private WithEvents Tmr As New Timer 

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load 
    If (Process.GetProcessesByName(Process.GetCurrentProcess.ProcessName).Length > 1) Then 
     Application.Exit() 
    End If 
    Tmr.Enabled = False 
    Tmr.Interval = TimeSpan.FromSeconds(60).TotalMilliseconds 
    BackgroundWorker1.RunWorkerAsync() 
End Sub 

Private Sub NotifyIcon1_MouseDoubleClick(sender As Object, e As MouseEventArgs) Handles NotifyIcon1.MouseDoubleClick 
    playsong = False 
    Try 


     ' Create a request for the URL. 
     Dim request As WebRequest = _ 
      WebRequest.Create("http://example.com/example.aspx") 
     ' If required by the server, set the credentials. 
     request.Credentials = CredentialCache.DefaultCredentials 
     ' Get the response. 
     Dim response As WebResponse = request.GetResponse() 
     ' Display the status. 
     Console.WriteLine(CType(response, HttpWebResponse).StatusDescription) 
     ' Get the stream containing content returned by the server. 
     Dim dataStream As Stream = response.GetResponseStream() 
     ' Open the stream using a StreamReader for easy access. 
     Dim reader As New StreamReader(dataStream) 
     ' Read the content. 
     Dim responseFromServer As String = reader.ReadToEnd() 
     ' Display the content. 
     Console.WriteLine(responseFromServer) 
     ' Clean up the streams and the response. 
     reader.Close() 
     response.Close() 

     Dim responseArray() As String 
     responseArray = Split(responseFromServer, "|") 

     Dim D As New Data 
     D.maxcalls = responseArray(0) 
     D.cph = responseArray(1) 
     D.mht = responseArray(2) 
     D.alarm = responseArray(3) 
     Form2.startsong(D) 
    Catch ex As Exception 

    End Try 
    playsong = True 
End Sub 

Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExitToolStripMenuItem.Click 
    Application.Exit() 
    End 
End Sub 

Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork 
    Try 
     If waittimer = 180000 Then 
      Tmr.Interval = waittimer 
      Tmr.Start() 
      waittimer = 60000 
     Else 
      waittimer = 60000 
     End If 

     ' Create a request for the URL. 
     Dim request As WebRequest = _ 
      WebRequest.Create("http://example.com/example.aspx") 
     ' If required by the server, set the credentials. 
     request.Credentials = CredentialCache.DefaultCredentials 
     ' Get the response. 
     Dim response As WebResponse = request.GetResponse() 
     ' Display the status. 
     Console.WriteLine(CType(response, HttpWebResponse).StatusDescription) 
     ' Get the stream containing content returned by the server. 
     Dim dataStream As Stream = response.GetResponseStream() 
     ' Open the stream using a StreamReader for easy access. 
     Dim reader As New StreamReader(dataStream) 
     ' Read the content. 
     Dim responseFromServer As String = reader.ReadToEnd() 
     ' Display the content. 
     Console.WriteLine(responseFromServer) 
     ' Clean up the streams and the response. 
     reader.Close() 
     response.Close() 

     Dim responseArray() As String 
     responseArray = Split(responseFromServer, "|") 

     Dim D As New Data 
     D.maxcalls = responseArray(0) 
     D.cph = responseArray(1) 
     D.mht = responseArray(2) 
     D.alarm = responseArray(3) 
     D.forcealarm = False 
     e.Result = D 
    Catch ex As Exception 
     Dim D As New Data 
     D.maxcalls = 404 
     D.cph = 404 
     D.mht = 404 
     D.alarm = True 
     D.forcealarm = True 
     e.Result = D 
    End Try 

    Tmr.Interval = waittimer 
End Sub 

Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted 
    If Not IsNothing(e.Result) Then 
     Dim strtime As String 
     Dim englandtime = System.TimeZoneInfo.ConvertTime(Now, TimeZoneInfo.FindSystemTimeZoneById("UTC")) 
     strtime = DatePart(Microsoft.VisualBasic.DateInterval.Hour, englandtime) & DatePart(Microsoft.VisualBasic.DateInterval.Minute, englandtime) 

     Dim D As Data = DirectCast(e.Result, Data) 
     If D.forcealarm = True Then 
      Form2.startsong(D) 
     End If 
     If D.alarm Then 
      If strtime < 730 And strtime > 0 Then 

      Else 
       Form2.startsong(D) 
      End If 
     End If 
    End If 
    Tmr.Start() 
End Sub 

Private Sub Tmr_Tick(sender As Object, e As System.EventArgs) Handles Tmr.Tick 
    Tmr.Stop() 
    BackgroundWorker1.RunWorkerAsync() 
End Sub 

End Class 

Public Class Data 
Public Property maxcalls As Integer 
Public Property cph As Integer 
Public Property mht As Integer 
Public Property alarm As Boolean 
Public Property forcealarm As Boolean 
End Class 

Form2

Public Class Form2 
Public audio As New AudioFile(My.Application.Info.DirectoryPath & "\Help.mp3") 
Public Sub startsong(ByVal D As Data) 
    Me.Show() 
    MHTvalue.Text = D.mht.ToString 
    Maxcallsvalue.Text = D.maxcalls 
    CPHvalue.Text = D.cph 
    If Form1.playsong = True Then 
     audio.Play() 
    End If 

End Sub 

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 
    ' Me.Close() 
    audio.Stop() 
    Form1.waittimer = 180000 
End Sub 

Private Sub Form2_Closing(sender As Object, e As EventArgs) Handles MyBase.Load 
    audio.Stop() 
    Form1.waittimer = 180000 
End Sub 

Private Sub Form2_Minimize(sender As Object, e As EventArgs) Handles MyBase.Load 
    audio.Stop() 
    Form1.waittimer = 180000 
End Sub 
+0

Что это "не" делает? Из быстрого просмотра вашего кода, похоже, вы пытаетесь установить таймер на form1, from form2, в то время как ваш form1, который вы используете, не является экземпляром исходного экземпляра form1? –

+0

Я пытаюсь изменить таймер, который используется для получения результатов от 60 секунд до получаса. form1 просто сидит в лотке уведомлений – Imsopov

+0

Я не вижу кода в форме2, который фактически получает запущенный экземпляр формы1? Просто ссылаясь на форму1, как это, ссылается на пустую копию формы1, а не на экземпляр формы1 уже запущен. –

ответ

0

То, вероятно, потому, что таймер на оригинальном form1, например, никогда не получить повторно настроен код. Вместо этого вы устанавливаете таймер на новую копию формы 1, которая не работает (показывается).

Вам необходимо получить исполняемый экземпляр формы1, который вы первоначально открыли. Техника, которую я использую для чего-то вроде этого, заключается в том, чтобы пометить мою форму, которую я буду искать, а затем пройти через экземпляры формы, которые в настоящее время выполняются, получить мою форму через свой тег, установив найденную форму, равную объекту, с которым я работаю, и THEN используют свойства/методы этой формы.

Установите метку формы1 на «myTag».

Тогда на форме 2:

 For Each f As Form In My.Application.OpenForms 

      If Not f.InvokeRequired Then 
       'Can access the form directly. 

       If f.Tag = "myTag" Then 
        'this is my form 
        Dim fcast As New form1 
        fcast = f 
        fcast.<---- use your methods/properties... 
       End If 

      End If 

     Next 
0

Просто измените:

Public Property waittimer As Integer 

To:

Public Property waittimer As Integer 
    Get 
     Return Tmr.Interval 
    End Get 
    Set(value As Integer) 
     If value > 0 Then 
      Tmr.Interval = value 
     End If 
    End Set 
End Property 

Вы изменяли значение waittimer, но не фактический интервал() из Таймер. Это связывает их вместе.

Смежные вопросы