Jump to content

Recommended Posts

Posted

Um bem Aja a todos

Pretendo colocar texto numérico ( 1 2 3 4 5 6 7 8 9) num button com os alinhamentos que as propriedades conferem, a finalidade é ajudar a resolver o SUdoku, mas não sei como fazer.

Tenho este código mas não executa o que pretendo

Agradecia umas dicas. Obrigado

 Private Sub Button2_KeyPress(sender As Object, e As KeyPressEventArgs) Handles Button2.KeyPress
        Dim KeyAscii As Short = CShort(Asc(e.KeyChar))

        If butModoNumeros.Text = "Modo Espera 1-2-3" Then

            KeyAscii = CShort(SoNumeros(KeyAscii))

            If KeyAscii = 0 Then
                e.Handled = True
                Button2.Text = ""
            Else
                Button2.Text = e.KeyChar
                Button2.Font = New Font("Microsoft Sans Serif", 8)

                If e.KeyChar = "1" Then Button2.TextAlign = ContentAlignment.TopLeft
                If e.KeyChar = "2" Then Button2.TextAlign = ContentAlignment.TopCenter
                If e.KeyChar = "3" Then Button2.TextAlign = ContentAlignment.TopRight
            End If
        Else

            'Por numeros normais
            KeyAscii = CShort(SoNumeros(KeyAscii))
            If KeyAscii = 0 Then
                e.Handled = True
                Button2.Text = ""
            Else
                Button2.Text = e.KeyChar
            End If

            If Not SolutionShown Then

                ' Call VerificarCasasPreenchidas()

                For i As Integer = 1 To 81
                        If CurButtons(i).Text <> SudokuSolution(i) Then
                            ' solFound = False
                            Exit Sub
                        End If
                    Next i

                    lblDone.Visible = True
            End If

        End If


    End Sub
Posted

Não estou a perceber bem o que queres. Queres meter um puzzle todo de Sudoku num botão?

10 REM Generation 48K!
20 INPUT "URL:", A$
30 IF A$(1 TO 4) = "HTTP" THEN PRINT "400 Bad Request": GOTO 50
40 PRINT "404 Not Found"
50 PRINT "./M6 @ Portugal a Programar."

 

Posted

Ah, queres colocar num determinado quadrado do Sudoku os botões com os números possíveis para essa posição. É isso?

10 REM Generation 48K!
20 INPUT "URL:", A$
30 IF A$(1 TO 4) = "HTTP" THEN PRINT "400 Bad Request": GOTO 50
40 PRINT "404 Not Found"
50 PRINT "./M6 @ Portugal a Programar."

 

Posted

Não propriamente, os botões já os tenho como podes verificar através do pedaço de código que enviei.

E consigo colocar um dos números ( de 1 a 9) no texto do button, no entanto preciso de colocar outos numeros possiveis para a resolução do puzzle.

Posted

Consegui aceder, não consegui foi compreender o que pretendes...

Falta-te o quê? Colocar o texto nos outros botões?
 

10 REM Generation 48K!
20 INPUT "URL:", A$
30 IF A$(1 TO 4) = "HTTP" THEN PRINT "400 Bad Request": GOTO 50
40 PRINT "404 Not Found"
50 PRINT "./M6 @ Portugal a Programar."

 

Posted (edited)

Bom dia M6

Vou tentar ser mais explicito. Na imagem apresenta o Sudoku com alguns números iniciais (botões Cremes) e botões azuis que são os números que faltam para a resolução.

Num dos botões azuis eu coloco o 7 que é o numero definitivo no puzzle, mas no botão azul que tem o 2 pode ser qualquer numero (1,2,4,5,8 etc). O que pretendo é conseguir colocar nos botões azuis  os números que podem servir como definitivos na resolução do puzzle, para no fim chegar ao numero certo na posição certa.

Com o código que apresento consigo colocar um caracter, mas  não consigo arranjar maneira de colocar mais nenhum.

Provavelmente não estou a utilizar o melhor processo para chegar onde pretendo.

Obrigado desde já pela atenção

Chamuanza

Edited by Chamuanza
completar uma frase
Posted

Para colocares o texto tens de juntar tudo numa string e atribuir essa string ao Text do botão.

10 REM Generation 48K!
20 INPUT "URL:", A$
30 IF A$(1 TO 4) = "HTTP" THEN PRINT "400 Bad Request": GOTO 50
40 PRINT "404 Not Found"
50 PRINT "./M6 @ Portugal a Programar."

 

Posted

Pois é mas não é isso que pretendo, mas sim ao colocar o focus num dos botões azuis atribuir o caractere de 1 a 9 com a disposição de alinhamento correspondente (TopLeft, TopCenter, etc).

Pelos vistos não tenho maneira de fazer isto, utilizando Buttons 

Posted

Isso não é possível.

10 REM Generation 48K!
20 INPUT "URL:", A$
30 IF A$(1 TO 4) = "HTTP" THEN PRINT "400 Bad Request": GOTO 50
40 PRINT "404 Not Found"
50 PRINT "./M6 @ Portugal a Programar."

 

Posted

Não sei se percebi bem, mas podes sempre usar a classe Graphics para desenhar os números no botão.

Cria um novo projecto com um botão e testa este código para ver se é isto que queres!

Tens é que carregar primeiro no botão para poderes digitares os números.. e só está a funcionar para os numeros 1,2,5 e 9.
 

Public Class Form1

    Dim numbersOnButton As New List(Of Integer)

    Private Function GetNumberPosition(ByVal n As Integer, ByRef font As Font, ByRef btn As Button) As Point

        Dim size As Size = TextRenderer.MeasureText("Q", font)

        If n = 1 Then Return New Point(0, CInt(size.Height / 2))
        If n = 2 Then Return New Point(CInt(btn.Width / 2 - size.Width / 2), CInt(size.Height / 2))
        ''..
        If n = 5 Then Return New Point(CInt(btn.Width / 2 - size.Width / 2), CInt(btn.Height / 2 - size.Height / 2))
        ''...
        If n = 9 Then Return New Point(btn.Width - size.Width, CInt(btn.Height - size.Height - size.Height / 2))
    End Function

    Private Sub Button1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles Button1.KeyPress
        Dim btn As Button = DirectCast(sender, Button)

        Dim n As Integer

        If Integer.TryParse(e.KeyChar, n) Then

            If n = 0 Then
                numbersOnButton.Clear()
            Else
                If numbersOnButton.Contains(n) Then
                    numbersOnButton.Remove(n)
                Else
                    numbersOnButton.Add(n)
                End If
            End If

            If btn.Image IsNot Nothing Then
                btn.Image.Dispose()
            End If

            Dim font = New Font("Microsoft Sans Serif", 8)

            Dim bmp As New Bitmap(btn.Width, btn.Height)

            Dim gfx As Graphics = Graphics.FromImage(bmp)
            'gfx.Clear(btn.BackColor)

            For Each item As Integer In numbersOnButton
                gfx.DrawString(item.ToString, font, Brushes.Black, GetNumberPosition(item, font, btn))
            Next

            btn.Image = bmp
        End If
    End Sub

End Class

Espero ter ajudado!

Depois diz se era mais o menos isto que querias!

Posted

Boa noite vikcch

Obrigado desde já pela ajuda. ( Não conseguia chegar a esta solução)

Numa primeira análise era isto que pretendia. Estou a testar como indicas. Vou acertar alguns elementos como a fonte e seguir o teu critério para os restantes números.

Posted (edited)

Também podes usar o evento Paint do botão, que até fica mais simples....

 

    Private Sub Button1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles Button1.KeyPress
        Dim btn As Button = DirectCast(sender, Button)

        Dim n As Integer

        If Integer.TryParse(e.KeyChar, n) Then

            If n = 0 Then
                numbersOnButton.Clear()
            Else
                If numbersOnButton.Contains(n) Then
                    numbersOnButton.Remove(n)
                Else
                    numbersOnButton.Add(n)
                End If
            End If

            btn.Refresh()

        End If
    End Sub

    Private Sub Button1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Button1.Paint
        Dim btn As Button = DirectCast(sender, Button)

        For Each item As Integer In numbersOnButton
            e.Graphics.DrawString(item.ToString, btn.Font, Brushes.Black, GetNumberPosition(item, btn.Font, btn))
        Next
    End Sub
Edited by vikcch
Posted

Boas vikcch

Testei a segunda sugestão que de facto se torna mais fácil como sugeres, mas como posso alterar o tamanho da fonte.

Pelo que entendo a rotina vais buscar a fonte a propriedade do form o que dá origem a um tamanho maior face a form inicial.

Chamuanza

Posted

este btn.Font é a fonte do botão.... que podes mudar nas propriedades do botão....

ou podes criar um novo objecto font como no primeiro exemplo que mandei... e convém fazer dispose do mesmo, ou usar dentro do bloco using...


 

    Private Sub Button1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Button1.Paint
        Dim btn As Button = DirectCast(sender, Button)

        Using font As New Font("Microsoft Sans Serif", 8)
            For Each item As Integer In numbersOnButton
                e.Graphics.DrawString(item.ToString, font, Brushes.Black, GetNumberPosition(item, font, btn))
            Next
        End Using

    End Sub
Posted

Boa Noite vikcch

Tenho vindo a implantar o código que me enviaste e acabo por verificar que em qualquer das hipóteses após marcar o primeiro button com os numeros ao passar o rato pelo segundo button os mesmos dados aparecem no segundo button. Estou baralhado 

Posted

Pois, tens de criar uma lista para cada botão...

ex:

Dim numbersOnButton1 As New List(Of Integer)
Dim numbersOnButton2 As New List(Of Integer)

ou uma lista de listas ou um array de listas....

 

Outra opção seria usares a propriedade Tag do botão e guardares lá os números inseridos, ou numa string ou numa lista...

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.