Современные решения

для защиты Windows приложений

и восстановления исходного кода

Visual Basic 6.0 - Help! VBS - "Лишний" час в TimeReceived (MAPI.Session)


Re: Help! VBS - "Лишний" час в TimeReceived (MAPI.Session)

Hello, Vladislav!
You wrote to <All>to All on 05 Dec 04 21:40:38:


VN> Ага... Всё прекрасно работает... Вот только _ДатаВремя_ писем,

VN> (полученное через "TimeSent" и "TimeReceived") _отличается_ от

VN> *реального* (больше) на _один_ час. Приходится грубо вычитать...

VN> В MSDN (CDO 1.2.1 Objects, Properties, and Methods) ничего не

VN> нашёл...

VN> Где копать?

Похоже на траблы с летним/зимним временем... Посмотри, что там с часовыми
поясами и всем таким.

(Дизклеймер: я с Exchange-ом никогда не работал, и это просто предположение,
взятое с потолка.)
* Origin: "Oh, no!" said the cat. (2:5080/1003.16)

регулярные выражения

Hello All.

недавно я спрашивал про сабж. теперь нашел доку в инете. думаю, интересно будет многим.

=== Cut ===
Regular Expressions

Regular expressions are used to match patterns of text, enabling you to manipulate text easily. The regular expression object in VBScript is called RegExp, and has three properties, and three methods.

To use the RegExp object in Visual Basic, select "VBScript Regular Expressions" from the Project, References menu. The RegExp object is then instantiated using the New keyword, as in the following example.

Dim objRE As New RegExp
' When you've finished,
' release the object from memory
Set objRE = Nothing

The following table describes the Properties of the RegExp Object.
RegExp Object's Properties
Property Example Description
Pattern

objRE.Pattern = "[a-z]"
The regular expression used for the match. The characters that define a regular expression are exaplained later in this tutorial. The pattern in the example matches the lowercase letters, a through to z.
IgnoreCase

objRE.IgnoreCase = False
A Boolean value to determine whether the match is case sensitive. By default, IgnoreCase is True.
Global

objRE.Global = True
A Boolean value to determine whether to match the first pattern in the string, or all possible matches. By default, Global is False.

The following table describes the Methods of the RegExp Object.
RegExp Object's Methods
Method Description
Test

The Test method returns True if the regular expression pattern is found in the string, otherwise it returns False. The following example matches the word "Stud" in "Juicy Studio", and outputs an "Expression found" message.

Dim objRE As New RegExp
Dim strExample As String
objRE.Pattern = "Stud"
strExample = "Juicy Studio"
' Test if a match is found
If objRE.Test(strExample) = True Then
MsgBox "Expression found", vbInformation, "RegExp"
Else
MsgBox "Expression not found", vbInformation, "RegExp"
End If
Set objRE = Nothing
Replace

The Replace method returns a string with occurences of the regular expression pattern replaced with a new string. The replace method takes two arguments, the original string, and the pattern to replace. The following example replaces all occurences of "flat" to "juicy". The output is, "My juicy mate has a juicy tyre". If the Global property was not set in the example, the output would be, "My juicy mate has a flat tyre".

Dim objRE As New RegExp
Dim strExample As String
objRE.Pattern = "flat"
objRE.Global = True
strExample = "My flat mate has a flat tyre."
' Replace occurences of "flat" with "juicy"
strExample = objRE.Replace(strExample, "juicy")
MsgBox strExample, vbInformation, "RegExp"
Set objRE = Nothing
Execute

The Execute method extends the functionality of the test method by returning a collection containing a Match object for each regular expression found in the string.

Dim objRE As New RegExp
Dim objMatches As MatchCollection
Dim objMatch As Match
Dim strExample As String
objRE.Pattern = "evil"
objRE.Global = True
strExample = "See no evil, hear no evil, speak no evil."
' Get all matches for evil
Set objMatches = objRE.Execute(strExample)
If objMatches.Count > 0 Then

For Each objMatch In objMatches
Debug.Print objMatch.Value & " found at position ";
Debug.Print objMatch.FirstIndex
Next
Else
Debug.Print "The expression was not found"
End If
Set objMatches = Nothing
Set objRE = Nothing

The above example returns the following:

evil found at position 7
evil found at position 21
evil found at position 36

If the Global property was not set, only the first match at position 7 would be found in the search string.
Pattern Matching

The following table lists the special characters that may be used to macth patterns with the regular expression object.
Special Characters
Character Example Matches
\

objRE.Pattern = "\d"

Used to find literal or special characters. In this example, the pattern matches a digit.
^

objRE.Pattern = "^Lemon"

The match must occur at the beginning of the string. In the example, the pattern matches strings that start with the string, "Lemon".
$

objRE.Pattern = "Lemon$"

The match must occur at the end of the string. In the example, the pattern matches strings that end with the string, "Lemon".
*

objRE.Pattern = "L*"

Matches zero or more times. In the example, the pattern matches a string of L's if they are present, otherwise an empty string.
+

objRE.Pattern = "L+"

Matches one or more times. In the example, the pattern matches a string of L's. If no L's are present, a match will not be found.
?

objRE.Pattern = "L?"

Matches zero or one time. In the example, the pattern matches a single "L"if present, otherwise an empty string.
.

objRE.Pattern = ".."

Matches any character except new lines. In the example, the pattern matches the first two characters.
\b

objRE.Pattern = "\bLe"
objRE.Pattern = "on\b"

Defines the boundary for the word. The first example matches any word in the expression that starts with "Le". The second example matches any word in the expression that ends with "on".
\B

objRE.Pattern = "\BLe"
objRE.Pattern = "on\B"

Ensures the match is not on the boundary of a word. The first example matches any word in the expression that contains "Le", but doesn't start with "Le". The second example matches any word in the expression that contains "on", but doesn't end with "on".
\d

objRE.Pattern = "\d"

Used to match any single digit between 0 and 9. The example matches the first single digit in the expression.
\D

objRE.Pattern = "\D"

Used to match any non-digit. The example matches the first non-digit in the expression.
\s

objRE.Pattern = "\s"

Used to match any single white-space characters. The example matches the first white-space character.
\S

objRE.Pattern = "\S"

Used to match any single non white-space character. The example matches the first non white-space character.
\w

objRE.Pattern = "\w"

Used to match any character, digit or underscore. The example matches the first character, digit, or underscore.
\W

objRE.Pattern = "\W"

Used to match anything other than a character, digit or underscore. The example matches the first occurence of anything other than a character, digit, or underscore.
\xnn

objRE.Pattern = "\x41"

Used to match the ASCII character represented by the hexadecimal number nn. The ASCII character for 'A' is 65. The hexadecimal value is 41. The example matches the first occurence of an A.
[]

objRE.Pattern = "[aeiou]"

Used to match any of the enclosed characters.
[^]

objRE.Pattern = "[^aeiou]"

The first match that is not in the enclosed characters.
[c-c]

objRE.Pattern = "[a-z]"

Used to match a range of characters. The example matches the first lowercase character.
{n}

objRE.Pattern = "w{3}"

Used to match n occurences of the previous character. The example matches "www" if three or more W's are found together in the string.
{n,}

objRE.Pattern = "w{3,}"

Used to match at least n occurences of the previous character.If there were four w's in the example, it would match "wwww".
{m,n}

objRE.Pattern = "w{3,5}"

Used to match between m and n occurences of the previous character. The example tries to match between three and five w's.
()

objRE.Pattern = "(em)"

Brackets are used for grouping. The value found is stored, and may be used later for referencing. This technique is called backreferencing.
|

objRE.Pattern = "a|e"

Matches either of the character to the side of the operator. In the example, the first match of either an a or an e is found.
Regular Expression Patterns

The following are example of some commonly used regular expression patterns.
Web Addresses or Emails

The following example could be used to match URLs or Email Addresses.

objRE.Pattern = "^\w+([\.-]?\w+)* [@] \w+([\.-]?\w+)*(\.\w{2,})+$"
HTML Tags

The following regular expression matches all tags in an HTML document. It can be combined with the Replace method to remove all tags from a document.

objRE.Pattern = "<\S[^>]*>"


The example can easily be extended to search for specific tags. The following example finds all image tags in a document.

objRE.Pattern = "<img\S[^>]*>"

Dates

The following regular expression may be used to validate a date.

objRE.Pattern = "^(3[01]|0[1-9]|[12]\d)\/(0[1-9]|1[012])\/\d{4}"

The following example of a RegExp object may be used to turn all tags brown in a RichTextFormatBox.

Dim objRE As New RegExp
Dim objMatch As Match
Dim objMatches As MatchCollection
Dim strXML As String
objRE.Pattern = "<\S[^>]*>"

objRE.Global = True
strXML = rtfXML.Text
If strXML <> "" Then

Set objMatches = objRE.Execute(strXML)
For Each objMatch In objMatches
rtfXML.SelStart = objMatch.FirstIndex
rtfXML.SelLength = objMatch.Length
rtfXML.SelColor = RGB(128, 0, 0)
Next objMatch
Set objMatch = Nothing
Set objMatches = Nothing
End If
Set objMatches = Nothing
Set objRE = Nothing
=== Cut ===

* Origin: (2:5020/829.610)

Re: pабочий стол

Мы где-то виделись, Dima?

05 Dec 04 13:24:32 в RU.VISUAL.BASIC Dima Grinenko -> Klim Omelchenko:


[...]
DG> Кому нужен пример, как достать из ярлыка всю информацию обращяйтесь. Все

DG> примеры только на Делфи.Мои извинения перед модератором.


Принято.

2All:

У Edanmo есть примеры работы с namespaces и т.п.; стоит посмотреть. Он же
оформил почти все интерфейсы среды в виде библиотеки типов tlb. Очень
юзабельно.

С эхотагом в папке upsupprt идет пример shelllnk; если его у вас нет, возьмите
с моего сайта.

Всего хорошего!
Дмитрий Козырев aka Master

* Origin: Дорогу осилит идущий. (2:5023/11.148)

Re: Поиск

From: "Dmitry Viazowkin" <vde [@] ufanet.ru>


Hi!

> Вариант Александра будет работать а) только на WinNT; б) в два раза

> медленнее InStr.

> Если вместо StrStrIW вызывать StrStrIA, которая есть на всех виндах, то

> будет работать в 5 раз медленнее InStr.


А ежели не через Declare, а через Typelib - дабы избежать преобразования
ANSI<>UNICODE?



--
With best regards
Dmitry Viazowkin


* Origin: Me? Organized??? (2:5020/400)

Поиск

Hi, Vladimir !

03 Дек 04 20:06, Vladimir Kochnev писал Max Irgiznov

AE>>> 4) Функцию InStr не пpедлагать! (Hету ее в 5-м VB).

AE>>> 5) 6-й ВБ тоже не пpедлагать ;)


AE>>> Буду благодаpен за помощь.

MI>> Регулярные выражения?

VK> а где они там в vb?

Как и обычно в Project->References->Microsoft VBSctipt Regular Expressions


Hе нравится МС и/или хочется острых ощущений то есть pcre(.dll)(Perl Compatible
Regular Expressions)

Good-bye, Vladimir !!! С вами был, есть и будет: Max Irgiznov [VS.NET]
[FreeBSD]
* Origin: Главное, ребята, перцем не стареть. (2:5051/36.20)

Re: Поиск

From: Alexander Asyabrik <belmis [@] mail.belpak.by>


Привет, A. Skrobov

Вы, было дело, писали 4 декабря 2004 г., 21:55:


AS> Да вы с ума что ли все сошли?!

AS> Скоро для умножения двух чисел будете вызывать MulDiv?


Да не ругайся же ты так! :-)
Это ж было дано чистА как вариант "разминки для ума", на случай если
бы в басике не было InStr (следи за тредом!). Лично у меня этого кода
никогда и не было, я просто взял вот и прикололся по случаю, не более
того. Хотя код мой и абсолютно рабочий, согласись.


AS> Вариант Александра будет работать а) только на WinNT;



=======
Unlike system libraries such as User32 and Kernel32, Shlwapi comes
with both ANSI and Unicode support, even on Windows 95/98.
=======

AS> б) в два раза медленнее InStr.



/Кстати, при существенном увеличении размера строки, в которой идет
поиск, этот разрыв еще больше увеличивается/


AS> Если вместо StrStrIW вызывать StrStrIA, которая есть на всех виндах,


Hа всякий случай теперь по-русски: в виндах есть ОБЕ эти функции, но
не во всех виндах, а только в тех где установлен IE 4.0 и выше (то
есть, там где есть SHLWAPI.DLL начиная от версии 4.71 и выше).

AS> то будет работать в 5 раз медленнее InStr.


Твой же пример у меня на Win98se с StrStrIA показал результат в два
раза _лучший_, чем с StrStrIW. А на NT, видимо, будет все наоборот.

AS> Соответственно не понимаю, где рульность и за что спасибо...


"Злые вы, уйду я от вас" (с) :-(


--
С уважением, Alexander
2:49:29 AM
* Origin: Talk.Mail.Ru (2:5020/400)

Поиск (и не только)

Пpивет Roman,
05 декабpя 04 ты писал(а) по поводу *Поиск. *
RY>>>>> Функция INSTR есть в VB5 и в любом MS-BASIC, начиная с QBasic и

RY>>>>> QuickBasic. Регистp в VB5 задается последним флагом.

======= Сгpызено моей собакой ========
AS>> это часом не клон TRS-80? (я пpосто не в куpсе) Если да, то там

AS>> INSTR должен быть.

RY> В бейсике для Радио86, в отличие от спектpума, есть функции Mid$, Left$,

RY> Right$, а вот INSTR я в упоp не помню. Я не знаю, чей это клон.

RY> Hасколько я помню, оно софтово совместимо с "Микpошей".

В спектpуме насколько помню использовалась констpукция типа (2 то 5) вместо мида, лефта и pайта.
Очень даже юзабельная была фича. Часто нехватает в циклах пpи обpаботке стpок. Хотя не знаю быстpее или медленнее она pаботала бы. :)

Тут буквально на днях поpазился pазнице в скоpости такой вещи: вывожу текст в RTB по стpокам (после вывода каждой стpоки делаю фоpматиpование последней).
Сначала использовал в пpоцедуpе Len(.Text) для вычисления длины текста в RTB. Hо на "больших" (для кого как, а для FIDO больших) сообщений ощущалась явная тоpмознутость - сообщение побольше (а это обычно FAQ'и и пpавила) выводилось иногда по 40-50 секунд. Уже всё что только можно сделал: и из цикла убpал наpужу почти все условия, и пеpед началом цикла опpеделял гpаницы массива стpок и использовал в цикле эти значения сохpанённые в пеpеменных - всё без толку - тоpмоза да и только.
Решил попользовать API. Только не пинайте ( :) ), был сильно удивлён скоpостью, пpи использовании вместо Len(.Text) функции API GetWindowTextLength (в написании могу ошибаться).
Скоpость возpосла на поpядки...
Может быть и ошибаюсь, но мне кажется чего же легче - посчитать в цикле (посимвольно) количество символов в поле. Ан нет, видимо делается что-то ещё...

MS всё пpодумали, а метод к RTB возpащающий длину текста не пpикpутили..
Hо это так, к слову о pаботе со стpоковыми пеpеменными.

Всех благ тебе, Roman.
ICQ 177792013 FmMB200016700
*Hа уши давит* - C.C.Catch - How Does It Feel
* Origin: http://www.r-demidow.front.ru/FBR/index.htm (2:5015/112.35)

Re: Как обнаружить процесс

From: "Sergey Broudkov" <broudkov [@] pointltd.com>


Hello, Roman!
You wrote to Sergey Broudkov on Fri, 03 Dec 2004 15:37:11 +0300:

SB>> Сдается мне, у тебя VB5. Там ИМХО AddressOf еще не придумали.


RY> #%$ [@] %!!! Каждому, кто мнит себя экспертом - на досуге считать различия

RY> между VB5 и VB6, уже их всех по сто раз пережевывали. Есть в VB5

RY> AddressOf


Зачем же так эмоционально? :( Hаписал же - ИМХО. Могу я, #%$ [@] %, ошибться,
или нет?

--
Regards,
Sergey Broudkov
sbpro [@] geocities.com
ICQ #4841919
А может, в реестре чего подправить? d;--D

* Origin: Demos online service (2:5020/400)

Re: Прозрачный контейнер

From: "Sergey Broudkov" <broudkov [@] pointltd.com>


Hello, Dmitriy!
You wrote to Sergey Broudkov on Fri, 03 Dec 2004 10:18:50 +0300:

SB>> но, к сожалению, VB-шные окна не обрабатывают WM_PRINT или

SB>> WM_PRINTCLIENT :(


DK> А стандартные окна Windows (EDIT, STATIC, BUTTON) поддерживают это

DK> сообщение?


Hе знаю, должны, по идее. А причем тут стандартные окна?

--
Regards,
Sergey Broudkov
sbpro [@] geocities.com
ICQ #4841919
А может, в реестре чего подправить? d;--D

* Origin: Demos online service (2:5020/400)

Re: Прозрачный контейнер

From: "Sergey Broudkov" <broudkov [@] pointltd.com>


Hello, A!
You wrote to Dmitriy Kozyrev on Fri, 03 Dec 2004 22:42:35 +0300:

SB>>> но, к сожалению, VB-шные окна не обрабатывают WM_PRINT или

SB>>> WM_PRINTCLIENT :(

DK>> А стандартные окна Windows (EDIT, STATIC, BUTTON) поддерживают это

DK>> сообщение?

A> Имхо всё, что принтскринится - его обрабатывает...


Принтскрин тут никаким боком. Там картинка берется с экранного DC.

A> С трудом верится, что стандартные контролы VB - нет. Сергей, хорошо

A> проверял? :-)


И не первый раз :) Еще пару лет назад пытался, по другому поводу, но с тем
же результатом. SendMessage возвращает успешное завершение, но в DC пусто.

A> Hа самом деле, а что мешает создать свой DC


Это-то, конечно, ничто не мешает :)

A> и рисовать в нём?


Мне-то рисовать там ничего не мешает :) Hо мне ж не самому там рисовать
надо, мне надо, чтоб VB-шные (и не только - мало ли кто чего в этот
контейнер положит) контролы _сами_ себя рисовали.

A> А ту же процедуру отрисовки себя в произвольном DC вызывать из

A> UserControl_Paint. Единственное ограничение - что рисовать всё придётся

A> через АПИ - в этом случае вряд ли существенно, так?


И как, например, я грид через API нарусую, если он тоже не захочет сам это
сделать?

--
Regards,
Sergey Broudkov
sbpro [@] geocities.com
ICQ #4841919
А может, в реестре чего подправить? d;--D

* Origin: Demos online service (2:5020/400)