Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)

Iniciado por Eleкtro, 18 Diciembre 2012, 22:23 PM

0 Miembros y 11 Visitantes están viendo este tema.

Eleкtro

HardwareStress

( click en la imagen para descargar la librería o el código fuente )


HardwareStress es una biblioteca .NET que proporciona un mecanismo para estresar los recursos de hardware, como la CPU, disco o memoria RAM.

Como cualquier otro software enfocado para estresar  los recursos de hardware, usted debe usarlo bajo su propio riesgo. No me responsabilizo de un error de hardware.




Donaciones

Cualquier código dentro del espacio de nombres "DevCase" se distribuye libremente como parte del código fuente comercial de "DevCase for .NET Framework".

Tal vez te gustaría considerar comprar este conjunto de bibliotecas para apoyarme. Puede hacer un montón de cosas con mis bibliotecas para una gran cantidad de temáticas diversas, no solo relacionadas con hardware, etc.

Aquí hay un enlace a la página de compra:

Muchas gracias.




Uso

El uso es muy simple, hay 3 clases: CpuStress, DiskStress y MemoryStress que proporciona un método Allocate() para comenzar a estresar los recursos, y un método Deallocate() para detenerlo.




Ejemplos de uso

CPU Stress
Código (vbnet) [Seleccionar]
Using cpuStress As New CpuStress()
    Dim percentage As Single = 20.5F 20.50%

    Console.WriteLine("Allocating CPU usage percentage...")
    cpuStress.Allocate(percentage)
    Thread.Sleep(TimeSpan.FromSeconds(5))
    Console.WriteLine("Instance CPU average usage percentage: {0:F2}%", cpuStress.InstanceCpuPercentage)
    Console.WriteLine("Process  CPU average usage percentage: {0:F2}%", cpuStress.ProcessCpuPercentage)
    Console.WriteLine()

    Console.WriteLine("Deallocating CPU usage percentage...")
    cpuStress.Deallocate()
    Thread.Sleep(TimeSpan.FromSeconds(5))
    Console.WriteLine("Instance CPU average usage percentage: {0:F2}%", cpuStress.InstanceCpuPercentage)
    Console.WriteLine("Process  CPU average usage percentage: {0:F2}%", cpuStress.ProcessCpuPercentage)
End Using



Disk Stress
Código (vbnet) [Seleccionar]
Using diskStress As New DiskStress()
    Console.WriteLine("Allocating disk I/O read and write operations...")
    diskStress.Allocate(fileSize:=1048576) 1 MB

    Thread.Sleep(TimeSpan.FromSeconds(10))

    Console.WriteLine("Stopping disk I/O read and write operations...")
    diskStress.Deallocate()

    Console.WriteLine()
    Console.WriteLine("Instance disk I/O read operations count: {0} (total of files read)", diskStress.InstanceReadCount)
    Console.WriteLine("Process  disk I/O read operations count: {0}", diskStress.ProcessReadCount)
    Console.WriteLine()
    Console.WriteLine("Instance disk I/O read data (in bytes): {0} ({1:F2} GB)", diskStress.InstanceReadBytes, (diskStress.InstanceReadBytes / 1024.0F ^ 3))
    Console.WriteLine("Process  disk I/O read data (in bytes): {0} ({1:F2} GB)", diskStress.ProcessReadBytes, (diskStress.ProcessReadBytes / 1024.0F ^ 3))
    Console.WriteLine()
    Console.WriteLine("Instance disk I/O write operations count: {0} (total of files written)", diskStress.InstanceWriteCount)
    Console.WriteLine("Process  disk I/O write operations count: {0}", diskStress.ProcessWriteCount)
    Console.WriteLine()
    Console.WriteLine("Instance disk I/O written data (in bytes): {0} ({1:F2} GB)", diskStress.InstanceWriteBytes, (diskStress.InstanceWriteBytes / 1024.0F ^ 3))
    Console.WriteLine("Process  disk I/O written data (in bytes): {0} ({1:F2} GB)", diskStress.ProcessWriteBytes, (diskStress.ProcessWriteBytes / 1024.0F ^ 3))
End Using



Memory Stress
Código (vbnet) [Seleccionar]
Using memStress As New MemoryStress()
    Dim memorySize As Long = 1073741824 1 GB

    Console.WriteLine("Allocating physical memory size...")
    memStress.Allocate(memorySize)
    Console.WriteLine("Instance Physical Memory Size (in bytes): {0} ({1:F2} GB)", memStress.InstancePhysicalMemorySize, (memStress.InstancePhysicalMemorySize / 1024.0F ^ 3))
    Console.WriteLine("Process  Physical Memory Size (in bytes): {0} ({1:F2} GB)", memStress.ProcessPhysicalMemorySize, (memStress.ProcessPhysicalMemorySize / 1024.0F ^ 3))
    Console.WriteLine()
    Console.WriteLine("Deallocating physical memory size...")
    memStress.Deallocate()
    Console.WriteLine("Instance Physical Memory Size (in bytes): {0}", memStress.InstancePhysicalMemorySize)
    Console.WriteLine("Process  Physical Memory Size (in bytes): {0} ({1:F2} MB)", memStress.ProcessPhysicalMemorySize, (memStress.ProcessPhysicalMemorySize / 1024.0F ^ 2))
End Using









Eleкtro

#541
Generador aleatorio de párrafos

Código (vbnet) [Seleccionar]
Private Shared rng As New Random(Seed:=Environment.TickCount)

Código (vbnet) [Seleccionar]
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Generates a random paragraph using the specified set of words.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <param name="words">
''' The words that will be used to build paragraphs.
''' </param>
'''
''' <param name="numberOfParagraphs">
''' The number of paragraphs to generate.
''' </param>
'''
''' <param name="htmlFormatting">
''' Specifies whether or not to format paragraphs for HTML.
''' </param>
''' ----------------------------------------------------------------------------------------------------
''' <returns>
''' The resulting paragraph(s).
''' </returns>
''' ----------------------------------------------------------------------------------------------------
<DebuggerStepThrough>
Public Shared Function RandomParagraphGenerator(ByVal words As String(),
                                               ByVal numberOfParagraphs As Integer,
                                               ByVal htmlFormatting As Boolean) As String

   Dim sb As New StringBuilder()

   Dim nextWord As String
   Dim nextWordIndex As Integer
   Dim lastWordIndex As Integer

   For paragraphIndex As Integer = 0 To (numberOfParagraphs - 1)

       Dim phraseLen As Integer = rng.Next(2, 10)
       For phraseIndex As Integer = 0 To (phraseLen - 1)

           If (phraseIndex = 0) AndAlso (htmlFormatting) Then
               sb.Append("<p>")
           End If

           Dim wordLen As Integer = rng.Next(3, 15)
           Dim addComma As Boolean = (rng.NextDouble() < 50 / 100.0) ' 50% probability to add a comma in a phrase.
           Dim commaAmount As Integer = rng.Next(1, (wordLen - 1) \ 2)
           Dim commaIndices As New HashSet(Of Integer)
           For i As Integer = 0 To (commaAmount - 1)
               commaIndices.Add(rng.Next(1, (wordLen - 1)))
           Next i

           For wordIndex As Integer = 0 To (wordLen - 1)

               Do Until (nextWordIndex <> lastWordIndex)
                   nextWordIndex = rng.Next(0, words.Length)
               Loop
               lastWordIndex = nextWordIndex
               nextWord = words(nextWordIndex)

               If (wordIndex = 0) Then
                   sb.Append(Char.ToUpper(nextWord(0)) & nextWord.Substring(1))
                   Continue For
               End If
               sb.Append(" " & words(rng.Next(0, words.Length)))

               If (commaIndices.Contains(wordIndex)) AndAlso (addComma) Then
                   sb.Append(","c)
               End If

               If (wordIndex = (wordLen - 1)) Then
                   If (phraseIndex <> (phraseLen - 1)) Then
                       sb.Append(". ")
                   Else
                       sb.Append(".")
                   End If
               End If
           Next wordIndex

       Next phraseIndex

       If (htmlFormatting) Then
           sb.Append("</p>")
       End If

       sb.AppendLine(Environment.NewLine)

   Next paragraphIndex

   Return sb.ToString()
End Function


Modo de empleo:
Código (vbnet) [Seleccionar]
Dim words As String() = {
   "a", "ability", "able", "about", "above", "accept", "according", "account", "across",
   "act", "action", "activity", "actually", "add", "address", "administration", "admit",
   "adult", "affect", "after", "again", "against", "age", "agency", "agent", "ago", "agree",
   "agreement", "ahead", "air", "all", "allow", "almost", "alone", "along", "already", "also",
   "although", "always", "American", "among", "amount", "analysis", "and", "animal", "another",
   "answer", "any", "anyone", "anything", "appear", "apply", "approach", "area", "argue", "arm",
   "around", "arrive", "art", "article", "artist", "as", "ask", "assume", "at", "attack", "attention",
   "attorney", "audience", "author", "authority", "available", "avoid", "away", "baby", "back",
   "bed", "before", "begin", "behavior", "behind", "believe", "benefit", "best", "better", "between",
   "both", "box", "boy", "break", "bring", "brother", "budget", "build", "building", "business", "but",
   "buy", "by", "call", "camera", "campaign", "can", "cancer", "candidate", "capital", "car", "card",
   "care", "career", "carry", "case", "catch", "cause", "cell", "center", "central", "century", "certain",
   "choice", "choose", "church", "citizen", "city", "civil", "claim", "class", "clear", "clearly",
   "close", "coach", "cold", "collection", "college", "color", "come", "commercial", "common", "community",
   "consumer", "contain", "continue", "control", "cost", "could", "country", "couple", "course", "court",
   "cover", "create", "crime", "cultural", "culture", "cup", "current", "customer", "cut", "dark",
   "data", "daughter", "day", "dead", "deal", "death", "debate", "decade", "decide", "decision", "deep",
   "defense", "degree", "Democrat", "democratic", "describe", "design", "despite", "detail",
   "direction", "director", "discover", "discuss", "discussion", "disease", "do", "doctor", "dog",
   "door", "down", "draw", "dream", "drive", "drop", "drug", "during", "each", "early", "east", "easy",
   "eat", "economic", "economy", "edge", "education", "effect", "effort", "eight", "either", "election",
   "environmental", "especially", "establish", "even", "evening", "event", "ever", "every", "everybody",
   "everyone", "everything", "evidence", "exactly", "example", "executive", "exist", "expect",
   "experience", "expert", "explain", "eye", "face", "fact", "factor", "fail", "fall", "family",
   "fill", "film", "final", "finally", "financial", "find", "fine", "finger", "finish", "fire",
   "firm", "first", "fish", "five", "floor", "fly", "focus", "follow", "food", "foot", "for",
   "force", "foreign", "forget", "form", "former", "forward", "four", "free", "friend", "from",
   "front", "full", "fund", "future", "game", "garden", "gas", "general", "generation", "get",
   "girl", "give", "glass", "go", "goal", "good", "government", "great", "green", "ground",
   "group", "grow", "growth", "guess", "gun", "guy", "hair", "half", "hand", "hang", "happen",
   "happy", "hard", "have", "he", "head", "health", "hear", "heart", "heat", "heavy", "help",
   "her", "here", "herself", "high", "him", "himself", "his", "history", "hit", "hold", "home",
   "hope", "hospital", "hot", "hotel", "hour", "house", "how", "however", "huge", "human", "hundred",
   "husband", "I", "idea", "identify", "if", "image", "imagine", "impact", "important", "improve",
   "in", "include", "including", "increase", "indeed", "indicate", "individual", "industry",
   "information", "inside", "instead", "institution", "interest", "interesting", "international",
   "interview", "into", "investment", "involve", "issue", "it", "item", "its", "itself", "job",
   "join", "just", "keep", "key", "kid", "kill", "kind", "kitchen", "know", "knowledge", "land",
   "language", "large", "last", "late", "later", "laugh", "law", "lawyer", "lay", "lead", "leader",
   "learn", "least", "leave", "left", "leg", "legal", "less", "let", "letter", "level", "lie", "life",
   "light", "like", "likely", "line", "list", "listen", "little", "live", "local", "long", "look",
   "lose", "loss", "lot", "love", "low", "machine", "magazine", "main", "maintain", "major", "majority",
   "make", "man", "manage", "management", "manager", "many", "market", "marriage", "material", "matter",
   "may", "maybe", "me", "mean", "measure", "media", "medical", "meet", "meeting", "member",
   "memory", "mention", "message", "method", "middle", "might", "military", "million", "mind",
   "minute", "miss", "mission", "model", "modern", "moment", "money", "month", "more", "morning",
   "most", "mother", "mouth", "move", "movement", "movie", "Mr", "Mrs", "much", "music", "must",
   "my", "myself", "name", "nation", "national", "natural", "nature", "near", "nearly", "necessary",
   "need", "network", "never", "new", "news", "newspaper", "next", "nice", "night", "no", "none", "nor",
   "north", "not", "note", "nothing", "notice", "now", "number", "occur", "of", "off", "offer",
   "office", "officer", "official", "often", "oh", "oil", "ok", "old", "on", "once", "one", "only",
   "onto", "open", "operation", "opportunity", "option", "or", "order", "organization", "other",
   "others", "our", "out", "outside", "over", "own", "owner", "page", "pain", "painting", "paper",
   "parent", "part", "participant", "particular", "particularly", "partner", "party", "pass",
   "past", "patient", "pattern", "pay", "peace", "people", "per", "perform", "performance",
   "perhaps", "period", "person", "personal", "phone", "physical", "pick", "picture",
   "piece", "place", "plan", "plant", "play", "player", "PM", "point", "police", "policy",
   "political", "politics", "poor", "popular", "population", "position", "positive",
   "possible", "power", "practice", "prepare", "present", "president", "pressure",
   "pretty", "prevent", "price", "private", "probably", "problem", "process", "produce",
   "product", "production", "professional", "professor", "program", "project", "property", "protect",
   "prove", "provide", "public", "pull", "purpose", "push", "put", "quality", "question", "quickly",
   "quite", "race", "radio", "raise", "range", "rate", "rather", "reach", "read", "ready", "real",
   "reality", "realize", "really", "reason", "receive", "recent", "recently", "recognize", "record",
   "red", "reduce", "reflect", "region", "relate", "relationship", "religious", "remain", "remember",
   "remove", "report", "represent", "Republican", "require", "research", "resource", "respond", "response",
   "responsibility", "rest", "result", "return", "reveal", "rich", "right", "rise", "risk", "road",
   "rock", "role", "room", "rule", "run", "safe", "same", "save", "say", "scene", "school", "science",
   "scientist", "score", "sea", "season", "seat", "second", "section", "security", "see", "seek",
   "seem", "sell", "send", "senior", "sense", "series", "serious", "serve", "service", "set", "seven",
   "show", "side", "sign", "significant", "similar", "simple", "simply", "since", "sing", "single",
   "sister", "sit", "site", "situation", "six", "size", "skill", "skin", "small", "smile", "so",
   "social", "society", "soldier", "some", "somebody", "someone", "something", "sometimes", "son",
   "specific", "speech", "spend", "sport", "spring", "staff", "stage", "stand", "standard", "star",
   "start", "state", "statement", "station", "stay", "step", "still", "stock", "stop", "store",
   "story", "strategy", "street", "strong", "structure", "student", "study", "stuff", "style",
   "subject", "success", "successful", "such", "suddenly", "suffer", "suggest", "summer", "support",
   "sure", "surface", "system", "table", "take", "talk", "task", "tax", "teach", "teacher", "team",
   "technology", "television", "tell", "ten", "tend", "term", "test", "than", "thank", "that", "the",
   "their", "them", "themselves", "then", "theory", "there", "these", "they", "thing", "think",
   "third", "this", "those", "though", "thought", "thousand", "threat", "three", "through", "throughout",
   "throw", "thus", "time", "to", "today", "together", "tonight", "too", "top", "total", "tough",
   "toward", "town", "trade", "traditional", "training", "travel", "treat", "treatment", "tree",
   "trial", "trip", "trouble", "true", "truth", "try", "turn", "TV", "two", "type", "under", "understand",
   "unit", "until", "up", "upon", "us", "use", "usually", "value", "various", "very", "victim",
   "view", "violence", "visit", "voice", "vote", "wait", "walk", "wall", "want", "war", "watch", "water",
   "way", "we", "weapon", "wear", "week", "weight", "well", "west", "western", "what", "whatever",
   "when", "where", "whether", "which", "while", "white", "who", "whole", "whom", "whose", "why",
   "wide", "wife", "will", "win", "wind", "window", "wish", "with", "within", "without", "woman",
   "wonder", "word", "work", "worker", "world", "worry", "would", "write", "writer", "wrong", "yard",
   "yeah", "year", "yes", "yet", "you", "young", "your", "yourself"}

Dim paragraphs As String = RandomParagraphGenerator(words, numberOfParagraphs:=4, htmlFormatting:=False)
Console.WriteLine(paragraphs)


CitarFinish at, raise, movie exist page, including there, yard ground why, information everyone. Life full those finger instead simple central those scientist. Force road of pick your student social. Prevent plan heart site. Anyone door, explain control.

Process interest we high human occur agree page put. Left education according thus, structure fine second professor rather relationship guess instead maybe radio. Second process reason on, create west. Forget victim wrong may themselves out where occur sometimes. Wide candidate, newspaper, if purpose at assume draw month, American physical create. Sea sign describe white though want minute type to medical. Explain girl their most upon.

Suddenly drug writer follow must. Right choose, option one capital risk. Administration forget practice anything. Notice people take movie, dark, yes only. Inside either recent movement during particular wear husband particularly those legal. Suffer drug establish work. Guess two have garden value property realize dog people friend, hospital that.

Person movie north wrong thing group. Write exist church daughter up, why appear ahead growth, wife news protect. Save smile, impact improve direction trouble tax, scene, north nation, maybe hang face history. Cause lawyer true worker season, more.




Generador aleatorio de texto 'Lorem Ipsum'

( ESTA FUNCIÓN SIMPLEMENTA HACE UNA LLAMADA AL GENERADOR DE PÁRRAFOS QUE HE PUBLICADO ARRIBA. )

Código (vbnet) [Seleccionar]
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Generates a random 'Lorem Ipsum' paragraph.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
''' <remarks>
''' Wikipedia article: <see href="https://en.wikipedia.org/wiki/Lorem_ipsum"/>
''' </remarks>
''' ----------------------------------------------------------------------------------------------------
''' <param name="numberOfParagraphs">
''' The number of paragraphs to generate.
''' </param>
'''
''' <param name="htmlFormatting">
''' Specifies whether or not to format paragraphs for HTML.
''' </param>
''' ----------------------------------------------------------------------------------------------------
''' <returns>
''' The resulting 'Lorem Ipsum' paragraph(s).
''' </returns>
''' ----------------------------------------------------------------------------------------------------
<DebuggerStepThrough>
Public Shared Function GenerateLoremIpsumText(ByVal numberOfParagraphs As Integer,
                                             ByVal htmlFormatting As Boolean) As String

   Dim words As String() = {
       "abhorreant", "accommodare", "accumsan", "accusam", "accusamus", "accusata", "ad",
       "adhuc", "adipisci", "adipiscing", "admodum", "adolescens", "adversarium", "aeque",
       "aeterno", "affert", "agam", "albucius", "alia", "alienum", "alii", "aliquam",
       "aliquando", "aliquid", "aliquip", "alterum", "amet", "an", "ancillae", "animal",
       "antiopam", "apeirian", "aperiam", "aperiri", "appareat", "appellantur", "appetere",
       "argumentum", "assentior", "assueverit", "assum", "at", "atomorum", "atqui", "audiam",
       "audire", "augue", "autem", "blandit", "bonorum", "brute", "case", "causae", "cetero",
       "ceteros", "choro", "cibo", "civibus", "clita", "commodo", "commune", "complectitur",
       "comprehensam", "conceptam", "concludaturque", "conclusionemque", "congue", "consectetuer",
       "consequat", "consequuntur", "consetetur", "constituam", "constituto", "consul", "consulatu",
       "contentiones", "convenire", "copiosae", "corpora", "corrumpit", "cotidieque", "cu", "cum",
       "debet", "debitis", "decore", "definiebas", "definitionem", "definitiones", "delectus",
       "delenit", "deleniti", "delicata", "delicatissimi", "democritum", "denique", "deseruisse",
       "deserunt", "deterruisset", "detracto", "detraxit", "diam", "dicam", "dicant", "dicat",
       "diceret", "dicit", "dico", "dicta", "dictas", "dicunt", "dignissim", "discere", "disputando",
       "disputationi", "dissentias", "dissentiet", "dissentiunt", "docendi", "doctus", "dolor",
       "dolore", "dolorem", "dolores", "dolorum", "doming", "duis", "duo", "ea", "eam", "efficiantur",
       "efficiendi", "ei", "eirmod", "eius", "elaboraret", "electram", "eleifend", "eligendi", "elit",
       "elitr", "eloquentiam", "enim", "eos", "epicurei", "epicuri", "equidem", "erant", "erat",
       "eripuit", "eros", "errem", "error", "erroribus", "eruditi", "esse", "essent", "est", "et",
       "etiam", "eu", "euismod", "eum", "euripidis", "everti", "evertitur", "ex", "exerci", "expetenda",
       "expetendis", "explicari", "fabellas", "fabulas", "facer", "facete", "facilis", "facilisi",
       "facilisis", "falli", "fastidii", "ferri", "feugait", "feugiat", "fierent", "forensibus",
       "fugit", "fuisset", "gloriatur", "graece", "graeci", "graecis", "graeco", "gubergren", "habemus",
       "habeo", "harum", "has", "hendrerit", "hinc", "his", "homero", "honestatis", "id", "idque",
       "ignota", "iisque", "illud", "illum", "impedit", "imperdiet", "impetus", "in", "inani", "inciderint",
       "incorrupte", "indoctum", "inermis", "inimicus", "insolens", "instructior", "integre", "intellegam",
       "intellegat", "intellegebat", "interesset", "interpretaris", "invenire", "invidunt", "ipsum",
       "iracundia", "iriure", "iudicabit", "iudico", "ius", "iusto", "iuvaret", "justo", "labitur",
       "laboramus", "labore", "labores", "laoreet", "latine", "laudem", "legendos", "legere", "legimus",
       "liber", "liberavisse", "libris", "lobortis", "lorem", "lucilius", "ludus", "luptatum", "magna",
       "maiestatis", "maiorum", "malis", "malorum", "maluisset", "mandamus", "mazim", "mea", "mediocrem",
       "mediocritatem", "mei", "meis", "mel", "meliore", "melius", "menandri", "mentitum", "minim",
       "minimum", "mnesarchum", "moderatius", "modo", "modus", "molestiae", "molestie", "mollis", "movet",
       "mucius", "mundi", "munere", "mutat", "nam", "natum", "ne", "nec", "necessitatibus", "neglegentur",
       "nemore", "nibh", "nihil", "nisl", "no", "nobis", "noluisse", "nominati", "nominavi", "nonumes",
       "nonumy", "noster", "nostro", "nostrud", "nostrum", "novum", "nulla", "nullam", "numquam", "nusquam",
       "oblique", "ocurreret", "odio", "offendit", "officiis", "omittam", "omittantur", "omnes", "omnesque",
       "omnis", "omnium", "oporteat", "oportere", "option", "oratio", "ornatus", "partem", "partiendo",
       "patrioque", "paulo", "per", "percipit", "percipitur", "perfecto", "pericula", "periculis", "perpetua",
       "persecuti", "persequeris", "persius", "pertinacia", "pertinax", "petentium", "phaedrum", "philosophia",
       "placerat", "platonem", "ponderum", "populo", "porro", "posidonium", "posse", "possim", "possit",
       "postea", "postulant", "praesent", "pri", "prima", "primis", "principes", "pro", "probatus", "probo",
       "prodesset", "prompta", "propriae", "purto", "putant", "putent", "quaeque", "quaerendum", "quaestio",
       "qualisque", "quando", "quas", "quem", "qui", "quidam", "quis", "quo", "quod", "quodsi", "quot",
       "rationibus", "rebum", "recteque", "recusabo", "referrentur", "reformidans", "regione", "reprehendunt",
       "reprimique", "repudiandae", "repudiare", "reque", "ridens", "sadipscing", "saepe", "sale", "salutandi",
       "salutatus", "sanctus", "saperet", "sapientem", "scaevola", "scribentur", "scripserit", "scripta",
       "scriptorem", "sea", "sed", "semper", "senserit", "sensibus", "sententiae", "signiferumque", "similique",
       "simul", "singulis", "sint", "sit", "soleat", "solet", "solum", "soluta", "sonet", "splendide", "stet",
       "suas", "suavitate", "summo", "sumo", "suscipiantur", "suscipit", "tacimates", "tale", "tamquam", "tantas",
       "tation", "te", "tempor", "temporibus", "theophrastus", "tibique", "timeam", "tincidunt", "tollit",
       "torquatos", "tota", "tractatos", "tritani", "ubique", "ullamcorper", "ullum", "unum", "urbanitas", "usu",
       "ut", "utamur", "utinam", "utroque", "vel", "velit", "veniam", "verear", "veri", "veritus", "vero",
       "verterem", "vide", "viderer", "vidisse", "vidit", "vim", "viris", "virtute", "vis", "vitae", "vituperata",
       "vituperatoribus", "vivendo", "vivendum", "vix", "vocent", "vocibus", "volumus", "voluptaria",
       "voluptatibus", "voluptatum", "voluptua", "volutpat", "vulputate", "wisi", "zril"}

   Dim str As String = RandomParagraphGenerator(words, numberOfParagraphs, htmlFormatting)

   If (htmlFormatting) Then
       Return str.Insert(3, "Lorem ipsum dolor sit amet. ")
   Else
       Return str.Insert(0, "Lorem ipsum dolor sit amet. ")
   End If

End Function


Modo de empleo:

Código (vbnet) [Seleccionar]
Dim loremIpsum As String = GenerateLoremIpsumText(numberOfParagraphs:=4, htmlFormatting:=True)
Console.WriteLine(loremIpsum)


Citar<p>Lorem ipsum dolor sit amet. Placerat vulputate tollit cum vivendo adipiscing nemore duo salutandi mollis. Fabellas malis, eros solet rationibus. Assum suas inermis, at veri prompta modo scaevola, ad. Percipitur ceteros semper vituperata feugait disputationi cotidieque soluta. Efficiendi facilisi zril percipit putant quando id quas nobis civibus natum. Pertinax maluisset vidisse oratio autem eripuit repudiandae ea suas eros illum oratio aliquid. Fabulas porro, integre oportere.</p>

<p>Virtute mediocritatem, vim erant nisl. Legendos postea saperet postea putent nihil facilisi nominati omnis. Facilisis persequeris scaevola alterum probatus vulputate denique pericula ullamcorper eloquentiam oporteat purto mediocritatem.</p>

<p>Veniam petentium delectus delicatissimi malis voluptua mentitum dissentias interpretaris verear quis utamur albucius verear. Quo reformidans, definitiones facilis. Conclusionemque quaestio voluptaria populo delicata sit viris mediocrem vulputate voluptatum eloquentiam. Quas an, bonorum cibo audiam commune volutpat. Vis ullamcorper scriptorem omnis facilisis sententiae hendrerit. Oporteat atomorum prompta suavitate idque accommodare ius oblique graece graecis interpretaris nemore. Meliore albucius commune qui suscipit definitiones vidit docendi facilisi forensibus quis. Equidem dolore expetendis iudico, delectus viderer timeam. Mediocrem molestie timeam, recteque, maluisset evertitur delicata.</p>

<p>Similique neglegentur temporibus alienum ad legimus scriptorem bonorum et appetere vide molestie. Mentitum feugait voluptatum illum detracto, tamquam vel ponderum mei illud, omnis paulo, ignota. Malorum lorem consul molestie interpretaris aperiri vituperatoribus, soluta enim vituperatoribus.</p>








Eleкtro

#542
ConsoleRectangle

Esto es el equivalente a la clase System.Drawing.Rectangle, para representar la posición y tamaño de un rectángulo (dibujable) en el búfer de salida de una consola.





Decisiones (o limitaciones) de diseño:

  • Las propiedades son de solo lectura (para quitarme de lios). Es decir, para hacer cambios en el tamaño o posición del rectángulo, hay que crear una nueva instancia. - ya no lo son
  • No permite la asignación de coordenadas negativas (puesto que tampoco lo permite el método Console.SetCursorPos()), ni un tamaño (anchura ni altura) igual a cero, aunque esto último no se tiene en cuenta si se usa el constructor por defecto.

EDITO: implementación extendida.
''' ----------------------------------------------------------------------------------------------------
''' <summary>
''' Stores a set of four integers that represent the location and size of a (printable) rectangle on a console output buffer.
''' </summary>
''' ----------------------------------------------------------------------------------------------------
<ComVisible(True)>
<Serializable>
Public Structure ConsoleRectangle

#Region " Properties "

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Gets or sets the location of this <see cref="ConsoleRectangle"/> on a console output buffer.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <value>
    ''' The location of this <see cref="ConsoleRectangle"/> on a console output buffer.
    ''' </value>
    ''' ----------------------------------------------------------------------------------------------------
    <Browsable(False)>
    Public Property Location As Point
        Get
            Return Me.location_
        End Get
        Set(value As Point)
            Me.UpdateLocation(value)
        End Set
    End Property
    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' ( Backing field of <see cref="ConsoleRectangle.Location"/> property. )
    ''' <para></para>
    ''' The location of this <see cref="ConsoleRectangle"/> on a console output buffer.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    Private location_ As Point

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Gets the x-coordinate of the upper-left corner of this <see cref="ConsoleRectangle"/>.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <value>
    ''' The x-coordinate of the upper-left corner of this <see cref="ConsoleRectangle"/>.
    ''' </value>
    ''' ----------------------------------------------------------------------------------------------------
    <Browsable(True)>
    Public ReadOnly Property X As Integer
        Get
            Return Me.Location.X
        End Get
    End Property

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Gets the y-coordinate of the upper-left corner of this <see cref="ConsoleRectangle"/>.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <value>
    ''' The y-coordinate of the upper-left corner of this <see cref="ConsoleRectangle"/>.
    ''' </value>
    ''' ----------------------------------------------------------------------------------------------------
    <Browsable(True)>
    Public ReadOnly Property Y As Integer
        Get
            Return Me.Location.Y
        End Get
    End Property

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Gets the y-coordinate of the top edge of this <see cref="ConsoleRectangle"/>.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <value>
    ''' The y-coordinate of the top edge of this <see cref="ConsoleRectangle"/>.
    ''' </value>
    ''' ----------------------------------------------------------------------------------------------------
    <Browsable(False)>
    Public ReadOnly Property Top As Integer
        Get
            Return Me.Y
        End Get
    End Property

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Gets the x-coordinate of the left edge of this <see cref="ConsoleRectangle"/>.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <value>
    ''' The x-coordinate of the left edge of this <see cref="ConsoleRectangle"/>.
    ''' </value>
    ''' ----------------------------------------------------------------------------------------------------
    <Browsable(False)>
    Public ReadOnly Property Left As Integer
        Get
            Return Me.X
        End Get
    End Property

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Gets the y-coordinate that is the sum of the <see cref="ConsoleRectangle.Y"/>
    ''' and <see cref="ConsoleRectangle.Height"/> property values of this <see cref="ConsoleRectangle"/>.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <value>
    ''' The y-coordinate that is the sum of the <see cref="ConsoleRectangle.Y"/>
    ''' and <see cref="ConsoleRectangle.Height"/> property values of this <see cref="ConsoleRectangle"/>.
    ''' </value>
    ''' ----------------------------------------------------------------------------------------------------
    <Browsable(False)>
    Public ReadOnly Property Bottom As Integer
        Get
            Return (Me.Y + Me.Height)
        End Get
    End Property

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Gets the x-coordinate that is the sum of <see cref="ConsoleRectangle.X"/>
    ''' and <see cref="ConsoleRectangle.Width"/> property values of this <see cref="ConsoleRectangle"/>.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <value>
    ''' The x-coordinate that is the sum of <see cref="ConsoleRectangle.X"/>
    ''' and <see cref="ConsoleRectangle.Width"/> property values of this <see cref="ConsoleRectangle"/>.
    ''' </value>
    ''' ----------------------------------------------------------------------------------------------------
    <Browsable(False)>
    Public ReadOnly Property Right As Integer
        Get
            Return (Me.X + Me.Width)
        End Get
    End Property

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Gets or sets the size of this <see cref="ConsoleRectangle"/>.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <value>
    ''' The size of this <see cref="ConsoleRectangle"/>.
    ''' </value>
    ''' ----------------------------------------------------------------------------------------------------
    <Browsable(False)>
    Public Property Size As Size
        Get
            Return Me.size_
        End Get
        Set(value As Size)
            Me.UpdateSize(value)
        End Set
    End Property
    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' ( Backing field of <see cref="ConsoleRectangle.Size"/> property. )
    ''' <para></para>
    ''' The size of this <see cref="ConsoleRectangle"/>.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    Private size_ As Size

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Gets the width of this <see cref="ConsoleRectangle"/>.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <value>
    ''' The width of this <see cref="ConsoleRectangle"/>.
    ''' </value>
    ''' ----------------------------------------------------------------------------------------------------
    <Browsable(True)>
    Public ReadOnly Property Width As Integer
        Get
            Return Me.Size.Width
        End Get
    End Property

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Gets the height of this <see cref="ConsoleRectangle"/>.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <value>
    ''' The height of this <see cref="ConsoleRectangle"/>.
    ''' </value>
    ''' ----------------------------------------------------------------------------------------------------
    <Browsable(True)>
    Public ReadOnly Property Height As Integer
        Get
            Return Me.Size.Height
        End Get
    End Property

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Gets or sets the character to print the left border of this <see cref="ConsoleRectangle"/> on a console output buffer.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <value>
    ''' The character to print the left border of this <see cref="ConsoleRectangle"/> on a console output buffer.
    ''' </value>
    ''' ----------------------------------------------------------------------------------------------------
    <Browsable(True)>
    Public Property CharLeft As Char

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Gets or sets the character to print the top border of this <see cref="ConsoleRectangle"/> on a console output buffer.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <value>
    ''' The character to print the top border of this <see cref="ConsoleRectangle"/> on a console output buffer.
    ''' </value>
    ''' ----------------------------------------------------------------------------------------------------
    <Browsable(True)>
    Public Property CharTop As Char

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Gets or sets the character to print the right border of this <see cref="ConsoleRectangle"/> on a console output buffer.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <value>
    ''' The character to print the right border of this <see cref="ConsoleRectangle"/> on a console output buffer.
    ''' </value>
    ''' ----------------------------------------------------------------------------------------------------
    <Browsable(True)>
    Public Property CharRight As Char

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Gets or sets the character to print the bottom border of this <see cref="ConsoleRectangle"/> on a console output buffer.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <value>
    ''' The character to print the bottom border of this <see cref="ConsoleRectangle"/> on a console output buffer.
    ''' </value>
    ''' ----------------------------------------------------------------------------------------------------
    <Browsable(True)>
    Public Property CharBottom As Char

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Tests whether all numeric properties of this System.Drawing.Rectangle have values of zero.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <value>
    ''' This property returns <see langword="True"/> if the
    ''' <see cref="ConsoleRectangle.Width"/>, <see cref="ConsoleRectangle.Height"/>,
    ''' <see cref="ConsoleRectangle.X"/>, and <see cref="ConsoleRectangle.Y"/> properties
    ''' of this <see cref="ConsoleRectangle"/> all have values of zero;
    ''' otherwise, <see langword="False"/>
    ''' </value>
    ''' ----------------------------------------------------------------------------------------------------
    <Browsable(False)>
    Public ReadOnly Property IsEmpty As Boolean
        Get
            Return (Me.Location = Point.Empty) AndAlso (Me.Size = Size.Empty)
        End Get
    End Property

#End Region

#Region " Constructors "

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Initializes a new instance of the <see cref="ConsoleRectangle"/> structure.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <param name="rect">
    ''' A <see cref="Rectangle"/> that contains the location and size for this <see cref="ConsoleRectangle"/>.
    ''' </param>
    ''' ----------------------------------------------------------------------------------------------------
    <DebuggerStepThrough>
    Public Sub New(ByVal rect As Rectangle)
        Me.New(rect.Location, rect.Size, "▌"c, "▀"c, "▐"c, "▄"c)
    End Sub

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Initializes a new instance of the <see cref="ConsoleRectangle"/> structure.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <param name="rect">
    ''' A <see cref="Rectangle"/> that contains the location and size for this <see cref="ConsoleRectangle"/>.
    ''' </param>
    '''
    ''' <param name="charLeft">
    ''' The character to print the left border of this <see cref="ConsoleRectangle"/> on a console output buffer.
    ''' </param>
    '''
    ''' <param name="charTop">
    ''' The character to print the top border of this <see cref="ConsoleRectangle"/> on a console output buffer.
    ''' </param>
    '''
    ''' <param name="charRight">
    ''' The character to print the right border of this <see cref="ConsoleRectangle"/> on a console output buffer.
    ''' </param>
    '''
    ''' <param name="charBottom">
    ''' The character to print the bottom border of this <see cref="ConsoleRectangle"/> on a console output buffer.
    ''' </param>
    ''' ----------------------------------------------------------------------------------------------------
    <DebuggerStepThrough>
    Public Sub New(ByVal rect As Rectangle,
                   ByVal charLeft As Char, ByVal charTop As Char,
                   ByVal charRight As Char, ByVal charBottom As Char)

        Me.New(rect.Location, rect.Size, charLeft, charTop, charRight, charBottom)

    End Sub

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Initializes a new instance of the <see cref="ConsoleRectangle"/> structure.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <param name="location">
    ''' The location for this <see cref="ConsoleRectangle"/> on a console output buffer.
    ''' </param>
    '''
    ''' <param name="size">
    ''' The size for this <see cref="ConsoleRectangle"/>.
    ''' </param>
    ''' ----------------------------------------------------------------------------------------------------
    <DebuggerStepThrough>
    Public Sub New(ByVal location As Point, ByVal size As Size)
        Me.New(location, size, "▌"c, "▀"c, "▐"c, "▄"c)
    End Sub

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Initializes a new instance of the <see cref="ConsoleRectangle"/> structure.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <param name="location">
    ''' The location for this <see cref="ConsoleRectangle"/> on a console output buffer.
    ''' </param>
    '''
    ''' <param name="size">
    ''' The size for this <see cref="ConsoleRectangle"/>.
    ''' </param>
    '''
    ''' <param name="charLeft">
    ''' The character to print the left border of this <see cref="ConsoleRectangle"/> on a console output buffer.
    ''' </param>
    '''
    ''' <param name="charTop">
    ''' The character to print the top border of this <see cref="ConsoleRectangle"/> on a console output buffer.
    ''' </param>
    '''
    ''' <param name="charRight">
    ''' The character to print the right border of this <see cref="ConsoleRectangle"/> on a console output buffer.
    ''' </param>
    '''
    ''' <param name="charBottom">
    ''' The character to print the bottom border of this <see cref="ConsoleRectangle"/> on a console output buffer.
    ''' </param>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <exception cref="ArgumentNullException">
    ''' </exception>
    ''' ----------------------------------------------------------------------------------------------------
    <DebuggerStepThrough>
    Public Sub New(ByVal location As Point, ByVal size As Size,
                   ByVal charLeft As Char, ByVal charTop As Char,
                   ByVal charRight As Char, ByVal charBottom As Char)

        Me.UpdateLocation(location)
        Me.UpdateSize(size)

        Me.CharLeft = charLeft
        Me.CharTop = charTop
        Me.CharRight = charRight
        Me.CharBottom = charBottom

    End Sub

#End Region

#Region " Public Methods "

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Writes the bounds of this <see cref="ConsoleRectangle"/> on the current console output buffer.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    <DebuggerStepThrough>
    Public Sub Write()
        For row As Integer = 0 To (Me.Height - 1)
            For column As Integer = 0 To (Me.Width - 1)
                If (row = 0) Then
                    Console.SetCursorPosition((Me.X + column), (Me.Y + row))
                    Console.Write(Me.CharTop)

                ElseIf (row = (Me.Height - 1)) Then
                    Console.SetCursorPosition((Me.X + column), (Me.Y + row))
                    Console.Write(Me.CharBottom)

                End If
            Next column

            Console.SetCursorPosition(Me.X, (Me.Y + row))
            Console.Write(Me.CharLeft)
            Console.SetCursorPosition(Me.X + (Me.Width - 1), (Me.Y + row))
            Console.Write(Me.CharRight)
        Next row
    End Sub

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Enlarges this <see cref="ConsoleRectangle"/> by the specified amount.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <param name="width">
    ''' The amount to inflate this <see cref="ConsoleRectangle"/> horizontally.
    ''' </param>
    '''
    ''' <param name="height">
    ''' The amount to inflate this <see cref="ConsoleRectangle"/> vertically.
    ''' </param>
    ''' ----------------------------------------------------------------------------------------------------
    <DebuggerStepThrough>
    Public Sub Inflate(ByVal width As Integer, ByVal height As Integer)
        Dim rc As Rectangle = Me
        rc.Inflate(width, height)
        Me.Size = rc.Size
    End Sub

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Enlarges this <see cref="ConsoleRectangle"/> by the specified amount.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <param name="size">
    ''' The amount to inflate this <see cref="ConsoleRectangle"/>.
    ''' </param>
    ''' ----------------------------------------------------------------------------------------------------
    <DebuggerStepThrough>
    Public Sub Inflate(ByVal size As Size)
        Me.Inflate(size.Width, size.Height)
    End Sub

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Adjusts the location of this <see cref="ConsoleRectangle"/> by the specified amount.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <param name="x">
    ''' The horizontal offset.
    ''' </param>
    '''
    ''' <param name="y">
    ''' The vertical offset.
    ''' </param>
    ''' ----------------------------------------------------------------------------------------------------
    <DebuggerStepThrough>
    Public Sub Offset(ByVal x As Integer, ByVal y As Integer)
        Dim rc As Rectangle = Me
        rc.Offset(x, y)
        Me.Location = rc.Location
    End Sub

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Adjusts the location of this <see cref="ConsoleRectangle"/> by the specified amount.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <param name="location">
    ''' The amount to offset the location.
    ''' </param>
    ''' ----------------------------------------------------------------------------------------------------
    <DebuggerStepThrough>
    Public Sub Offset(ByVal location As Point)
        Me.Offset(location.X, location.Y)
    End Sub

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Returns a <see cref="String"/> that represents this <see cref="ConsoleRectangle"/>.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <returns>
    ''' A <see cref="String"/> that represents this <see cref="ConsoleRectangle"/>.
    ''' </returns>
    ''' ----------------------------------------------------------------------------------------------------
    <DebuggerStepThrough>
    Public Overrides Function ToString() As String

        If (Me.Width = 1) AndAlso (Me.Height = 1) Then
            Return Me.CharLeft

        ElseIf (Me.Height = 1) Then
            Dim sb As New StringBuilder()
            Dim lastColumnIndex As Integer = (Me.Width - 1)
            For column As Integer = 0 To lastColumnIndex
                Select Case column
                    Case 0
                        sb.Append(Me.CharLeft)
                    Case lastColumnIndex
                        sb.Append(Me.CharRight)
                    Case Else
                        sb.Append(Me.CharTop)
                End Select
            Next column
            Return sb.ToString()

        ElseIf (Me.Width = 1) Then
            Dim sb As New StringBuilder()
            For row As Integer = 0 To (Me.Height - 1)
                sb.Append(Me.CharLeft)
                sb.AppendLine()
            Next row
            Return sb.ToString()

        Else
            Dim sb As New StringBuilder()
            Dim lastRowIndex As Integer = (Me.Height - 1)
            For row As Integer = 0 To lastRowIndex
                Select Case row
                    Case 0
                        sb.Append(Me.CharLeft)
                        sb.Append(New String(Me.CharTop, Math.Max((Me.Width - 2), 1)))
                        sb.Append(Me.CharRight)
                    Case lastRowIndex
                        sb.Append(Me.CharLeft)
                        sb.Append(New String(Me.CharBottom, Math.Max((Me.Width - 2), 1)))
                        sb.Append(Me.CharRight)
                    Case Else
                        sb.Append(Me.CharLeft)
                        sb.Append(New String(" "c, Math.Max((Me.Width - 2), 1)))
                        sb.Append(Me.CharRight)
                End Select
                sb.AppendLine()
            Next row
            Return sb.ToString()

        End If

    End Function

#End Region

#Region " Operators "

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Performs an implicit conversion from <see cref="ConsoleRectangle"/> to <see cref="Rectangle"/>.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <param name="rect">
    ''' The source <see cref="ConsoleRectangle"/>.
    ''' </param>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <returns>
    ''' The resulting <see cref="Rectangle"/>.
    ''' </returns>
    ''' ----------------------------------------------------------------------------------------------------
    <DebuggerStepThrough>
    Public Shared Widening Operator CType(ByVal rect As ConsoleRectangle) As Rectangle
        Return New Rectangle(rect.Location, rect.Size)
    End Operator

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Performs an implicit conversion from <see cref="Rectangle"/> to <see cref="ConsoleRectangle"/>.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <param name="rect">
    ''' The source <see cref="Rectangle"/>.
    ''' </param>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <returns>
    ''' The resulting <see cref="ConsoleRectangle"/>.
    ''' </returns>
    ''' ----------------------------------------------------------------------------------------------------
    <DebuggerStepThrough>
    Public Shared Widening Operator CType(rect As Rectangle) As ConsoleRectangle
        Return New ConsoleRectangle(rect)
    End Operator

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Tests whether two <see cref="Rectangle"/> and <see cref="ConsoleRectangle"/> structures have equal location and size.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <param name="rect">
    ''' The <see cref="Rectangle"/> to compare with the <see cref="ConsoleRectangle"/> structure.
    ''' </param>
    '''
    ''' <param name="consoleRect">
    ''' The <see cref="ConsoleRectangle"/> to compare with the <see cref="Rectangle"/> structure.
    ''' </param>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <returns>
    ''' <see langword="True"/> if the two <see cref="Rectangle"/> and <see cref="ConsoleRectangle"/> structures have equal location and size;
    ''' otherwise, <see langword="False"/>.
    ''' </returns>
    ''' ----------------------------------------------------------------------------------------------------
    <DebuggerStepThrough>
    Public Shared Operator =(rect As Rectangle, consoleRect As ConsoleRectangle) As Boolean
        Return (rect.Location = consoleRect.Location) AndAlso (rect.Size = consoleRect.Size)
    End Operator

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Determine whether two <see cref="Rectangle"/> and <see cref="ConsoleRectangle"/> structures differ in location or size.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <param name="rect">
    ''' The <see cref="Rectangle"/> to compare with the <see cref="ConsoleRectangle"/> structure.
    ''' </param>
    '''
    ''' <param name="consoleRect">
    ''' The <see cref="ConsoleRectangle"/> to compare with the <see cref="Rectangle"/> structure.
    ''' </param>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <returns>
    ''' <see langword="True"/> if the two <see cref="Rectangle"/> and <see cref="ConsoleRectangle"/> structures differ in location or size;
    ''' otherwise, <see langword="False"/>.
    ''' </returns>
    ''' ----------------------------------------------------------------------------------------------------
    <DebuggerStepThrough>
    Public Shared Operator <>(rect As Rectangle, consoleRect As ConsoleRectangle) As Boolean
        Return Not (rect = consoleRect)
    End Operator

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Tests whether two <see cref="ConsoleRectangle"/> structures have equal location, size and characters.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <param name="left">
    ''' The <see cref="ConsoleRectangle"/> structure that is to the left of the equality operator.
    ''' </param>
    '''
    ''' <param name="right">
    ''' The <see cref="ConsoleRectangle"/> structure that is to the right of the equality operator.
    ''' </param>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <returns>
    ''' <see langword="True"/> if the two <see cref="ConsoleRectangle"/> structures have equal location, size and characters;
    ''' otherwise, <see langword="False"/>.
    ''' </returns>
    ''' ----------------------------------------------------------------------------------------------------
    <DebuggerStepThrough>
    Public Shared Operator =(left As ConsoleRectangle, right As ConsoleRectangle) As Boolean
        Return (left.Location = right.Location) AndAlso
               (left.Size = right.Size) AndAlso
               (left.CharLeft = right.CharLeft) AndAlso
               (left.CharTop = right.CharTop) AndAlso
               (left.CharRight = right.CharRight) AndAlso
               (left.CharBottom = right.CharBottom)
    End Operator

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Tests whether two <see cref="ConsoleRectangle"/> structures differ in location, size or characters.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <param name="left">
    ''' The <see cref="ConsoleRectangle"/> structure that is to the left of the equality operator.
    ''' </param>
    '''
    ''' <param name="right">
    ''' The <see cref="ConsoleRectangle"/> structure that is to the right of the equality operator.
    ''' </param>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <returns>
    ''' <see langword="True"/> if if any of the two <see cref="ConsoleRectangle"/> structures differ in location, size or characters;
    ''' otherwise, <see langword="False"/>.
    ''' </returns>
    ''' ----------------------------------------------------------------------------------------------------
    <DebuggerStepThrough>
    Public Shared Operator <>(left As ConsoleRectangle, right As ConsoleRectangle) As Boolean
        Return Not (left = right)
    End Operator

#End Region

#Region " Private Methods "

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Updates the location value specified in <see cref="ConsoleRectangle.Location"/> property.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <param name="newLocation">
    ''' The new location.
    ''' </param>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <exception cref="ArgumentException">
    ''' Positive value is required for coordinate.
    ''' </exception>
    ''' ----------------------------------------------------------------------------------------------------
    <DebuggerStepThrough>
    Private Sub UpdateLocation(ByVal newLocation As Point)
        If (Me.location_ = newLocation) Then
            Exit Sub
        End If

        If (newLocation.X < 0) Then
            Throw New ArgumentException(paramName:=NameOf(newLocation),
                                        message:=String.Format("Positive value is required for '{0}' coordinate.", NameOf(newLocation.X)))

        ElseIf (newLocation.Y < 0) Then
            Throw New ArgumentException(paramName:=NameOf(newLocation),
                                        message:=String.Format("Positive value is required for '{0}' coordinate.", NameOf(newLocation.Y)))

        End If

        Me.location_ = newLocation
    End Sub

    ''' ----------------------------------------------------------------------------------------------------
    ''' <summary>
    ''' Updates the size value specified in <see cref="ConsoleRectangle.Size"/> property.
    ''' </summary>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <param name="newSize">
    ''' The new size.
    ''' </param>
    ''' ----------------------------------------------------------------------------------------------------
    ''' <exception cref="ArgumentException">
    ''' Value greather than zero is required.
    ''' </exception>
    ''' ----------------------------------------------------------------------------------------------------
    <DebuggerStepThrough>
    Private Sub UpdateSize(ByVal newSize As Size)
        If (Me.size_ = newSize) Then
            Exit Sub
        End If

        If (newSize.Width <= 0) Then
            Throw New ArgumentException(paramName:=NameOf(Size),
                                        message:=String.Format("Value greather than zero is required for '{0}'", NameOf(newSize.Width)))

        ElseIf (newSize.Height <= 0) Then
            Throw New ArgumentException(paramName:=NameOf(Size),
                                        message:=String.Format("Value greather than zero is required for '{0}'", NameOf(newSize.Height)))

        End If

        Me.size_ = newSize
    End Sub

#End Region

End Structure


Ejemplo de uso:
Public Module Module1

   Public Sub Main()
       Dim rc1Pos As New Point(2, Console.CursorTop + 2)
       Dim rc1 As New ConsoleRectangle(rc1Pos, New Size(32, 4), "▌"c, "▀"c, "▐"c, "▄"c)
       rc1.Write()

       Dim rc2Pos As New Point(2, Console.CursorTop + 2)
       Dim rc2 As New ConsoleRectangle(rc2Pos, New Size(32, 4), "X"c, "X"c, "X"c, "X"c)
       rc2.Write()

       Dim rc3Pos As New Point(2, Console.CursorTop + 2)
       Dim rc3 As New ConsoleRectangle(rc3Pos, New Size(11, 5), "▌"c, "▀"c, "▐"c, "▄"c)
       rc3.Write()

       Dim rc4Pos As New Point(rc3Pos.X + (rc3.Width \ 2), rc3Pos.Y + +(rc3.Height \ 2))
       Dim rc4 As New ConsoleRectangle(rc4Pos, rc3.Size, "X"c, "X"c, "X"c, "X"c)
       rc4.Write()

       Console.SetCursorPosition(rc1.X + 9, rc1.Y)
       Console.Write(" Hello World ")
       Console.SetCursorPosition(rc1.X + 6, rc1.Y + 2)
       Console.Write(" By ElektroStudios ")

       Console.CursorVisible = False
       Console.ReadKey(intercept:=True)
   End Sub

End Module








**Aincrad**

#543
VM Detector class

Una Pequeña class que codee para detectar la ejecución en maquinas virtuales.




Link (Actualizado) : AntiVM Class




Como usar ?

Agregar 1 Timer

Código (vbnet) [Seleccionar]
Public ProtectVM As AntiVM = New AntiVM

   Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
       ProtectVM.VM_Start()
       Anti_VM_Timer.Enabled = True
   End Sub

   Private Sub Anti_VM_Timer_Tick(sender As Object, e As EventArgs) Handles Anti_VM_Timer.Tick
       Dim Detection As Boolean = ProtectVM.IsVirtualMachinePresent
       Dim Description As String = ProtectVM.DescriptcionVM

       If Detection = True Then
          msgbox("VM detectada : " & Description)
       End If

   End Sub




**Aincrad**



Listar los Modulos de un Proceso. (Incluyendo su MainModule)

Código (vbnet) [Seleccionar]
Declare Function OpenProcess Lib "kernel32" (ByVal dwDesiredAccess As UInt32, ByVal bInheritHandle As Int32, ByVal dwProcessId As UInt32) As IntPtr

        Public Shared Function GetProcessModules(ByVal Process_Name As String) As String
            Dim DataS As New StringBuilder
            Dim pc As Process() = Process.GetProcessesByName(Process_Name)

            Dim hndProc As IntPtr = OpenProcess(&H2 Or &H8 Or &H10 Or &H20 Or &H400, 1, CUInt(pc(0).Id))
            If hndProc = IntPtr.Zero Then
                Return "Error"
            End If

            Dim ModulesCount As Integer = pc(0).Modules.Count - 1
            For index As Integer = 0 To ModulesCount
                DataS.Append(pc(0).Modules(index).FileName & vbNewLine)
            Next

            Return DataS.ToString
        End Function


Modo de Empleo :

Código (vbnet) [Seleccionar]
TextBox1.Text = GetProcessModules("ProcessName")






**Aincrad**

#545
Mi Vieja Clase para Injectar DLLs .



DestroyerInjector.vb

Código (vbnet) [Seleccionar]
'Hack Trainer | Private SDK
'Made by Destroyer | Discord : Destroyer#3527
'Creation date : 4/02/2017
'Last Update : 26/06/2019  - Minimal Update

Namespace DestroyerSDK

   Public Class Injector

#Region " Declare's "

       Declare Function OpenProcess Lib "kernel32" (ByVal dwDesiredAccess As UInt32, ByVal bInheritHandle As Int32, ByVal dwProcessId As UInt32) As IntPtr
       Declare Function CloseHandle Lib "kernel32" (ByVal hObject As IntPtr) As Int32
       Declare Function WriteProcessMemory Lib "kernel32" (ByVal hProcess As IntPtr, ByVal lpBaseAddress As IntPtr, ByVal buffer As Byte(), ByVal size As UInt32, ByRef lpNumberOfBytesWritten As IntPtr) As Boolean
       Declare Function GetProcAddress Lib "kernel32" (ByVal hModule As IntPtr, ByVal methodName As String) As IntPtr
       Declare Function GetModuleHandleA Lib "kernel32" (ByVal moduleName As String) As IntPtr
       Declare Function VirtualAllocEx Lib "kernel32" (ByVal hProcess As IntPtr, ByVal lpAddress As IntPtr, ByVal dwSize As IntPtr, ByVal flAllocationType As UInteger, ByVal flProtect As UInteger) As IntPtr
       Declare Function CreateRemoteThread Lib "kernel32" (ByVal hProcess As IntPtr, ByVal lpThreadAttribute As IntPtr, ByVal dwStackSize As IntPtr, ByVal lpStartAddress As IntPtr, ByVal lpParameter As IntPtr, ByVal dwCreationFlags As UInteger, ByVal lpThreadId As IntPtr) As IntPtr
       Declare Function GetPrivateProfileStringA Lib "kernel32" (ByVal lpAppName As String, ByVal lpKeyName As String, ByVal lpDefault As String, ByVal lpReturnedString As System.Text.StringBuilder, ByVal nSize As Integer, ByVal lpFileName As String) As Integer
       Declare Function WritePrivateProfileStringA Lib "kernel32" (ByVal lpAppName As String, ByVal lpKeyName As String, ByVal lpString As String, ByVal lpFileName As String) As Integer

#End Region

#Region " Method's "

       Private Shared Function CreateRemoteThread(ByVal procToBeInjected As Process, ByVal sDllPath As String) As Boolean
           Dim lpLLAddress As IntPtr = IntPtr.Zero
           Dim hndProc As IntPtr = OpenProcess(&H2 Or &H8 Or &H10 Or &H20 Or &H400, 1, CUInt(procToBeInjected.Id))
           If hndProc = IntPtr.Zero Then
               Return False
           End If
           lpLLAddress = GetProcAddress(GetModuleHandleA("kernel32.dll"), "LoadLibraryA")
           If lpLLAddress = CType(0, IntPtr) Then
               Return False
           End If
           Dim lpAddress As IntPtr = VirtualAllocEx(hndProc, CType(Nothing, IntPtr), CType(sDllPath.Length, IntPtr), CUInt(&H1000) Or CUInt(&H2000), CUInt(&H40))
           If lpAddress = CType(0, IntPtr) Then
               Return False
           End If
           Dim bytes As Byte() = System.Text.Encoding.ASCII.GetBytes(sDllPath)
           Dim ipTmp As IntPtr = IntPtr.Zero
           WriteProcessMemory(hndProc, lpAddress, bytes, CUInt(bytes.Length), ipTmp)
           If ipTmp = IntPtr.Zero Then
               Return False
           End If
           Dim ipThread As IntPtr = CreateRemoteThread(hndProc, CType(Nothing, IntPtr), IntPtr.Zero, lpLLAddress, lpAddress, 0, CType(Nothing, IntPtr))
           If ipThread = IntPtr.Zero Then
               Return False
           End If
           Return True
       End Function

       Public Shared Function InjectDLL(ByVal ProcessName As String, ByVal sDllPath As String) As Boolean
           Dim p As Process() = Process.GetProcessesByName(ProcessName)
           If p.Length <> 0 Then
               If Not CreateRemoteThread(p(0), sDllPath) Then
                   If p(0).MainWindowHandle <> CType(0, IntPtr) Then
                       CloseHandle(p(0).MainWindowHandle)
                   End If
                   Return False
               End If
               Return True
           End If
           Return False
       End Function

#End Region

   End Class

End Namespace




Modo de uso :


Código (vbnet) [Seleccionar]
 Dim InjectDll As Boolean = InjectDLL("ProcessGame", "DLL_Path")









**Aincrad**

#546
Un Control Recién salido del Horno , Literalmente lo hice ayer.

Adf.ly Clicker


Tal como dice el titulo, Con ella puedes generas visitas a tu Link Adf.ly ..


Código (vbnet) [Seleccionar]

---------------------------------------Parchado


Bueno Fue bueno mientras duro. pero ya fue Parchado el code. osea que ia no sirve, y no voy a actualizar.








**Aincrad**

#547
Bueno Comparto algunas funciones útiles por si creas algún Cheat en vb.net . las necesitaras.

Características :


  • GetCursorPosition ' De tipo Point , Devuelve la Posicion del Puntero del mause en el Escritorio
  • GetClientPosition  ' De tipo Point , Devuelve la Posicion de Alguna venta en el Escritorio [Juego / Applicacion]
  • GetClientCursorPosition ' De tipo Point , Devuelve la Posicion del Puntero del mause desde el Cliente  [Juego / Applicacion]
  • ShowCursor ' De tipo Bool , Muestra o Oculta el Cursor del mause
  • GetProcessHandle ' De tipo IntPtr , Obtienes el Handle de algun Proceso, By Elektro

Class WinMauseHelpersCore

Código (vbnet) [Seleccionar]
Imports System.Runtime.InteropServices

Public Class WinMauseHelpersCore


#Region " Pinvoke "

   <DllImport("user32.dll")> _
   Private Shared Function GetCursorPos(<[In](), Out()> ByRef pt As System.Drawing.Point) As Boolean
   End Function
   <DllImport("user32.dll", SetLastError:=True)> _
   Private Shared Function ScreenToClient(ByVal hWnd As IntPtr, ByRef lpPoint As System.Drawing.Point) As Boolean
   End Function
   <DllImport("user32.dll", CharSet:=CharSet.Auto)> _
   Private Shared Function GetClientRect(ByVal hWnd As System.IntPtr, ByRef lpRECT As RECT) As Integer
   End Function
   <DllImport("user32.dll", CharSet:=CharSet.Auto, ExactSpelling:=True)> _
   Public Shared Function ShowCursor(ByVal bShow As Boolean) As Integer
   End Function

#Region " Structures "

   <StructLayout(LayoutKind.Sequential)> _
   Public Structure RECT
       Private _Left As Integer, _Top As Integer, _Right As Integer, _Bottom As Integer

       Public Sub New(ByVal Rectangle As Rectangle)
           Me.New(Rectangle.Left, Rectangle.Top, Rectangle.Right, Rectangle.Bottom)
       End Sub
       Public Sub New(ByVal Left As Integer, ByVal Top As Integer, ByVal Right As Integer, ByVal Bottom As Integer)
           _Left = Left
           _Top = Top
           _Right = Right
           _Bottom = Bottom
       End Sub

       Public Property X As Integer
           Get
               Return _Left
           End Get
           Set(ByVal value As Integer)
               _Right = _Right - _Left + value
               _Left = value
           End Set
       End Property
       Public Property Y As Integer
           Get
               Return _Top
           End Get
           Set(ByVal value As Integer)
               _Bottom = _Bottom - _Top + value
               _Top = value
           End Set
       End Property
       Public Property Left As Integer
           Get
               Return _Left
           End Get
           Set(ByVal value As Integer)
               _Left = value
           End Set
       End Property
       Public Property Top As Integer
           Get
               Return _Top
           End Get
           Set(ByVal value As Integer)
               _Top = value
           End Set
       End Property
       Public Property Right As Integer
           Get
               Return _Right
           End Get
           Set(ByVal value As Integer)
               _Right = value
           End Set
       End Property
       Public Property Bottom As Integer
           Get
               Return _Bottom
           End Get
           Set(ByVal value As Integer)
               _Bottom = value
           End Set
       End Property
       Public Property Height() As Integer
           Get
               Return _Bottom - _Top
           End Get
           Set(ByVal value As Integer)
               _Bottom = value + _Top
           End Set
       End Property
       Public Property Width() As Integer
           Get
               Return _Right - _Left
           End Get
           Set(ByVal value As Integer)
               _Right = value + _Left
           End Set
       End Property
       Public Property Location() As Point
           Get
               Return New Point(Left, Top)
           End Get
           Set(ByVal value As Point)
               _Right = _Right - _Left + value.X
               _Bottom = _Bottom - _Top + value.Y
               _Left = value.X
               _Top = value.Y
           End Set
       End Property
       Public Property Size() As Size
           Get
               Return New Size(Width, Height)
           End Get
           Set(ByVal value As Size)
               _Right = value.Width + _Left
               _Bottom = value.Height + _Top
           End Set
       End Property

       Public Shared Widening Operator CType(ByVal Rectangle As RECT) As Rectangle
           Return New Rectangle(Rectangle.Left, Rectangle.Top, Rectangle.Width, Rectangle.Height)
       End Operator
       Public Shared Widening Operator CType(ByVal Rectangle As Rectangle) As RECT
           Return New RECT(Rectangle.Left, Rectangle.Top, Rectangle.Right, Rectangle.Bottom)
       End Operator
       Public Shared Operator =(ByVal Rectangle1 As RECT, ByVal Rectangle2 As RECT) As Boolean
           Return Rectangle1.Equals(Rectangle2)
       End Operator
       Public Shared Operator <>(ByVal Rectangle1 As RECT, ByVal Rectangle2 As RECT) As Boolean
           Return Not Rectangle1.Equals(Rectangle2)
       End Operator

       Public Overrides Function ToString() As String
           Return "{Left: " & _Left & "; " & "Top: " & _Top & "; Right: " & _Right & "; Bottom: " & _Bottom & "}"
       End Function

       Public Overloads Function Equals(ByVal Rectangle As RECT) As Boolean
           Return Rectangle.Left = _Left AndAlso Rectangle.Top = _Top AndAlso Rectangle.Right = _Right AndAlso Rectangle.Bottom = _Bottom
       End Function
       Public Overloads Overrides Function Equals(ByVal [Object] As Object) As Boolean
           If TypeOf [Object] Is RECT Then
               Return Equals(DirectCast([Object], RECT))
           ElseIf TypeOf [Object] Is Rectangle Then
               Return Equals(New RECT(DirectCast([Object], Rectangle)))
           End If

           Return False
       End Function
   End Structure

#End Region

   Public Function GetCursorPosition() As System.Drawing.Point
       Dim CursorPos As New System.Drawing.Point
       GetCursorPos(CursorPos)
       Return CursorPos
   End Function

   Public Function GetClientPosition(ByVal hWnd As IntPtr) As System.Drawing.Point
       Dim ClientPos As New System.Drawing.Point
       ScreenToClient(hWnd, ClientPos)
       Return ClientPos
   End Function

   Public Function GetClientCursorPosition(ByVal hWnd As IntPtr) As System.Drawing.Point
       Dim ClientCursorPos As New System.Drawing.Point
       Dim CursorPos As System.Drawing.Point = GetCursorPosition()
       Dim ClientPos As System.Drawing.Point = GetClientPosition(hWnd)
       ClientCursorPos = New System.Drawing.Point(CursorPos.X + ClientPos.X, CursorPos.Y + ClientPos.Y)
       Return ClientCursorPos
   End Function

   Public Function GetProcessHandle(ByVal ProcessName As String) As IntPtr
       If ProcessName.ToLower.EndsWith(".exe") Then ProcessName = ProcessName.Substring(0, ProcessName.Length - 4)
       Dim ProcessArray = Process.GetProcessesByName(ProcessName)
       If ProcessArray.Length = 0 Then Return Nothing Else Return ProcessArray(0).MainWindowHandle
   End Function

#End Region

End Class






**Aincrad**

Defender Watcher

Monitoriza la desactivacion em tiempo real del Windows Defender.

( click en la imagen para ir código fuente en Github)





Codigo Fuente

DefenderWatcher.vb

Código (vbnet) [Seleccionar]
' ***********************************************************************
' Author   : Destroyer
' Modified : 8-June-2021
' Github   : https://github.com/DestroyerDarkNess
' Twitter  : https://twitter.com/Destroy06933000
' ***********************************************************************
' <copyright file="DefenderWatcher.vb" company="S4Lsalsoft">
'     Copyright (c) S4Lsalsoft. All rights reserved.
' </copyright>
' ***********************************************************************

#Region " Usage Examples "

' ''' <summary>
' ''' The DefenderWatcher instance to monitor Windows Defender Realtime Status Changed.
' ''' </summary>
'Friend WithEvents DefenderMon As New DefenderWatcher

' ''' ----------------------------------------------------------------------------------------------------
' ''' <summary>
' ''' Handles the <see cref="DefenderWatcher.DefenderStatusChanged"/> event of the <see cref="DefenderMon"/> instance.
' ''' </summary>
' ''' ----------------------------------------------------------------------------------------------------
' ''' <param name="sender">
' ''' The source of the event.
' ''' </param>
' '''
' ''' <param name="e">
' ''' The <see cref="DefenderWatcher.DefenderStatusChangedEventArgs"/> instance containing the event data.
' ''' </param>
' ''' ----------------------------------------------------------------------------------------------------
'Private Sub DefenderMon_DefenderStatusChanged(ByVal sender As Object, ByVal e As DefenderWatcher.DefenderStatusChangedEventArgs) Handles DefenderMon.DefenderStatusChanged
'    Dim sb As New System.Text.StringBuilder
'    sb.AppendLine(" Defender Configuration change -  Windows Defender RealtimeMonitoring")
'    sb.AppendLine(String.Format("DisableRealtimeMonitoring......: {0}", e.TargetInstance.ToString))
'    sb.AppendLine(String.Format("Old Value......................: {0}", e.PreviousInstance.ToString))
'    Me.BeginInvoke(Sub()
'                       TextBox1.Text += (sb.ToString) & Environment.NewLine & Environment.NewLine
'                   End Sub)
'End Sub

#End Region

#Region " Imports "

Imports System.ComponentModel
Imports System.Management
Imports System.Windows.Forms

#End Region

Namespace Core.Engine.Watcher

    Public Class DefenderWatcher : Inherits NativeWindow : Implements IDisposable

#Region " Constructor "

        ''' ----------------------------------------------------------------------------------------------------
        ''' <summary>
        ''' Initializes a new instance of <see cref="DefenderWatcher"/> class.
        ''' </summary>
        ''' ----------------------------------------------------------------------------------------------------
        <DebuggerStepThrough>
        Public Sub New()

            Me.events = New EventHandlerList

        End Sub

#End Region

#Region " Properties "

        ''' ----------------------------------------------------------------------------------------------------
        ''' <summary>
        ''' Gets a value that determines whether the monitor is running.
        ''' </summary>
        ''' ----------------------------------------------------------------------------------------------------
        Public ReadOnly Property IsRunning As Boolean
            <DebuggerStepThrough>
            Get
                Return Me.isRunningB
            End Get
        End Property
        Private isRunningB As Boolean

#End Region

        Private Scope As New ManagementScope("root\Microsoft\Windows\Defender")
        Private WithEvents DefenderState As ManagementEventWatcher = New ManagementEventWatcher(Scope, New WqlEventQuery("SELECT * FROM __InstanceModificationEvent WITHIN 5 WHERE TargetInstance ISA 'MSFT_MpPreference' AND TargetInstance.DisableRealtimeMonitoring=True"))

#Region " Events "


        ''' ----------------------------------------------------------------------------------------------------
        ''' <summary>
        ''' A list of event delegates.
        ''' </summary>
        ''' ----------------------------------------------------------------------------------------------------
        Private ReadOnly events As EventHandlerList

        Public Custom Event DefenderStatusChanged As EventHandler(Of DefenderStatusChangedEventArgs)

            <DebuggerNonUserCode>
            <DebuggerStepThrough>
            AddHandler(ByVal value As EventHandler(Of DefenderStatusChangedEventArgs))
                Me.events.AddHandler("DefenderStatusChangedEvent", value)
            End AddHandler

            <DebuggerNonUserCode>
            <DebuggerStepThrough>
            RemoveHandler(ByVal value As EventHandler(Of DefenderStatusChangedEventArgs))
                Me.events.RemoveHandler("DefenderStatusChangedEvent", value)
            End RemoveHandler

            <DebuggerNonUserCode>
            <DebuggerStepThrough>
            RaiseEvent(ByVal sender As Object, ByVal e As DefenderStatusChangedEventArgs)
                Dim handler As EventHandler(Of DefenderStatusChangedEventArgs) =
                    DirectCast(Me.events("DefenderStatusChangedEvent"), EventHandler(Of DefenderStatusChangedEventArgs))

                If (handler IsNot Nothing) Then
                    handler.Invoke(sender, e)
                End If
            End RaiseEvent

        End Event

#End Region

        '   Dim oInterfaceType As String = TIBase?.Properties("DisableRealtimeMonitoring")?.Value.ToString() ' Prevent Defender Disable

        Public Sub DefenderState_EventArrived(ByVal sender As Object, ByVal e As EventArrivedEventArgs) Handles DefenderState.EventArrived
            Dim DefenderTargetInstance As Boolean = Nothing
            Dim DefenderPreviousInstance As Boolean = Nothing

            Using TIBase = CType(e.NewEvent.Properties("TargetInstance").Value, ManagementBaseObject)
                DefenderTargetInstance = CBool(TIBase.Properties("DisableRealtimeMonitoring").Value)
            End Using

            Using PIBase = CType(e.NewEvent.Properties("PreviousInstance").Value, ManagementBaseObject)
                DefenderPreviousInstance = CBool(PIBase.Properties("DisableRealtimeMonitoring").Value)
            End Using

            Me.OnDefenderStatusChanged(New DefenderStatusChangedEventArgs(DefenderTargetInstance, DefenderPreviousInstance))

        End Sub

#Region " Event Invocators "

        <DebuggerStepThrough>
        Protected Overridable Sub OnDefenderStatusChanged(ByVal e As DefenderStatusChangedEventArgs)

            RaiseEvent DefenderStatusChanged(Me, e)

        End Sub

#End Region

#Region " Events Data "

        Public NotInheritable Class DefenderStatusChangedEventArgs : Inherits EventArgs

#Region " Properties "

            Private ReadOnly TargetInstanceB As Boolean
            Public ReadOnly Property TargetInstance As Boolean
                <DebuggerStepThrough>
                Get
                    Return Me.TargetInstanceB
                End Get
            End Property

            Private ReadOnly PreviousInstanceB As Boolean
            Public ReadOnly Property PreviousInstance As Boolean
                <DebuggerStepThrough>
                Get
                    Return Me.PreviousInstanceB
                End Get
            End Property

#End Region

#Region " Constructors "

            <DebuggerNonUserCode>
            Private Sub New()
            End Sub

            <DebuggerStepThrough>
            Public Sub New(ByVal TI As Boolean, ByVal PI As Boolean)

                Me.TargetInstanceB = TI
                Me.PreviousInstanceB = PI

            End Sub

#End Region

        End Class

#End Region

#Region " Public Methods "

        ''' ----------------------------------------------------------------------------------------------------
        ''' <summary>
        ''' Starts monitoring.
        ''' </summary>
        ''' ----------------------------------------------------------------------------------------------------
        ''' <exception cref="Exception">
        ''' Monitor is already running.
        ''' </exception>
        ''' ----------------------------------------------------------------------------------------------------
        <DebuggerStepThrough>
        Public Overridable Sub Start()

            If (Me.Handle = IntPtr.Zero) Then
                MyBase.CreateHandle(New CreateParams)
                DefenderState.Start()
                 Me.isRunningB = True

            Else
                Throw New Exception(message:="Monitor is already running.")

            End If

        End Sub

        ''' ----------------------------------------------------------------------------------------------------
        ''' <summary>
        ''' Stops monitoring.
        ''' </summary>
        ''' ----------------------------------------------------------------------------------------------------
        ''' <exception cref="Exception">
        ''' Monitor is already stopped.
        ''' </exception>
        ''' ----------------------------------------------------------------------------------------------------
        <DebuggerStepThrough>
        Public Overridable Sub [Stop]()

            If (Me.Handle <> IntPtr.Zero) Then
                DefenderState.Stop()
                MyBase.DestroyHandle()
                Me.isRunningB = False

            Else
                Throw New Exception(message:="Monitor is already stopped.")

            End If

        End Sub

#End Region

#Region " IDisposable Implementation "

        ''' ----------------------------------------------------------------------------------------------------
        ''' <summary>
        ''' To detect redundant calls when disposing.
        ''' </summary>
        ''' ----------------------------------------------------------------------------------------------------
        Private isDisposed As Boolean

        ''' ----------------------------------------------------------------------------------------------------
        ''' <summary>
        ''' Releases all the resources used by this instance.
        ''' </summary>
        ''' ----------------------------------------------------------------------------------------------------
        <DebuggerStepThrough>
        Public Sub Dispose() Implements IDisposable.Dispose

            Me.Dispose(isDisposing:=True)
            GC.SuppressFinalize(obj:=Me)

        End Sub

        ''' ----------------------------------------------------------------------------------------------------
        ''' <summary>
        ''' Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        ''' Releases unmanaged and - optionally - managed resources.
        ''' </summary>
        ''' ----------------------------------------------------------------------------------------------------
        ''' <param name="isDisposing">
        ''' <see langword="True"/>  to release both managed and unmanaged resources;
        ''' <see langword="False"/> to release only unmanaged resources.
        ''' </param>
        ''' ----------------------------------------------------------------------------------------------------
        <DebuggerStepThrough>
        Protected Overridable Sub Dispose(ByVal isDisposing As Boolean)

            If (Not Me.isDisposed) AndAlso (isDisposing) Then

                Me.events.Dispose()
                Me.Stop()

            End If

            Me.isDisposed = True

        End Sub

#End Region

    End Class

End Namespace